springboot+websocket+angular 爱被打了一巴掌 2022-05-27 07:12 119阅读 0赞 **一、websocket服务端代码参考 另一篇博客 --> [传送门][Link 1]** **二、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** <div><button (click)="send()">点击</button></div> **六、启动java项目和angular项目 访问localhost:4200 点击按钮测试** [Link 1]: https://blog.csdn.net/zeketao/article/details/79930901
还没有评论,来说两句吧...