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';
複製代碼

參考的文章

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息