stompjs初探

629 阅读1分钟

一、客户端

1、框架

stompjs、create-react-app(redux+ts)

2、安装

①、安装Create-React-App(redux+ts)模板框架

create-react-app myapp --template redux-typescript
参考

github.com/reduxjs/cra…

②、安装stompjs

 npm i @stomp/stompjs@5.4.4
参考

www.npmjs.com/package/@st…

3、代码

①、定义websocket client

//定义websocket client
let client: Client | null = null;
export const testStomp=(): AppThunk => () => {
  const tempClient = new Client({
    brokerURL: 'ws://192.168.100.103:8081',
    stompVersions: new Versions([Versions.V1_2])
});
tempClient.onConnect = (frame) => {
  console.log('onConnect');
  //业务
};

tempClient.beforeConnect = () => {
  console.log('beforeConnect');
};
tempClient.onWebSocketClose = (evt) => {
  console.log('onWebSocketClose:' + JSON.stringify(evt ));
};
tempClient.onStompError = (frame) => {
  console.log('onStompError');
};
client = tempClient;
tempClient.activate();
};

②、某个事件或触发发送消息

  if(client){
        client.publish({
          destination: "",
          body: "testbody"
      });
      }

服务端

框架:

winows控制台应用程序,Flack插件

代码:

   public static void Main(string[] args)
        {
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://192.168.100.103:8081");
            ////握手时 客户端header中Sec-WebSocket-Protocol值为:v12.stomp
            //子协议协商系统,否则会报:
            //Error during WebSocket handshake: 
            //Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
            server.SupportedSubProtocols = new[] { "v12.stomp" };
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open....");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine("ClientMesssage:" + message);
                };

            });
            Console.ReadLine();
        }

文档

stompjs官方文档:github.com/stomp-js/st…

Flack插件文档:www.cnblogs.com/Jeffrey-Cho…