作者:轶乐-love万 | 来源:互联网 | 2023-09-15 08:34
一、websocket服务端代码参考另一篇博客--传送门二、ngnewsocket创建angulardemo项目ngnewsocket三、安装stompjsjs库npmin
一、websocket服务端代码参考 另一篇博客 --> 传送门
二、ng new socket 创建angular demo项目
ng new socket
三、安装 stompjs js库
npm install stompjs --save
四、app.component.ts 代码 (和js的写法大同小异)
import { Component } from '@angular/core';
const SockJS = require('sockjs-client');
const Stomp = require('stompjs');@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {title = 'app works!';stompClient: any;constructor() {const that = this;const socket = new SockJS('http://localhost:8080/websocket-server');this.stompClient = Stomp.over(socket);this.stompClient.connect({}, function (frame) {console.log('Connected: ' + frame);that.stompClient.subscribe('/topic/message', function (greeting) {alert(greeting);});}, function (err) {console.log('err', err);});}send() {this.stompClient.send('/server/send', {}, 'send');}
}
五、app.component.html
六、启动java项目和angular项目 访问localhost:4200 点击按钮测试