angular5+SpringBoot+Websocket

介绍

前端使用angular5框架,后端使用springboot,使用Websocket协议创建长链接css

SpringBoot

Using WebSocket to build an interactive web application 这是Spring官方的文档,找这么搭建就行。html

关键

注意上面代码中的几个地址

  • '/gs-guide-webscoket' 用于创建长链接前端

  • '/app/hello' 用于客户端sendjquery

  • '/topic/greeting' 用于订阅,客户端send后触发,将response发个订阅的客户端web

angular5

关键代码spring

import { Component } from '@angular/core';
import Stomp from 'stompjs';
import SockJS from 'sockjs-client';
import $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private serverUrl = 'http://localhost:8080/gs-guide-webscoket'
  private title = 'WebSockets chat';
  private stompClient;

  constructor(){
    this.initializeWebSocketConnection();
  }

  initializeWebSocketConnection(){
    let ws = new SockJS(this.serverUrl);
    this.stompClient = Stomp.over(ws);
    let that = this;
    this.stompClient.connect({}, function(frame) {
      that.stompClient.subscribe("/topic/greeting", (message) => {
        if(message.body) {
          $(".chat").append("<div class='message'>"+message.body+"</div>")
          console.log(message.body);
        }
      });
    });
  }

  sendMessage(message){
    this.stompClient.send("/app/hello" , {}, message);
    $('#input').val('');
  }

}
复制代码

angular中调用Js的方法

不是每次都管用,先记在这里后端

import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';
import * as $ from 'jquery';
复制代码

参考的文章

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息