一、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
<div><button (click)="send()">点击</button></div>
六、启动java项目和angular项目 访问localhost:4200 点击按钮测试