requestmapping默认是get还是post_手把手教你建立自己的聊天服务器,get起来

首先说一下python端使用方法(关注我,下一篇开放基于react的通信源码)

不废话,下载地址:https://download.csdn.net/download/u011643716/12822976

python连接websocket的方法

import jsonfrom ws4py.client.threadedclient import WebSocketClientclass CG_Client(WebSocketClient):    def opened(self):        req = '{"event":"subscribe", "channel":"eth_usdt.deep"}'        self.send(req)    def closed(self, code, reason=None):        print("Closed down:", code, reason)    def received_message(self, resp):        print respif __name__ == '__main__':    ws = None    try:    #peabody 可以更换为你的用户名        ws = CG_Client('ws://127.0.0.1:8080/socketServer/peabody')        ws.connect()        ws.run_forever()    except KeyboardInterrupt:        ws.close()

调用接口示例

http://127.0.0.10:8080/websocket/sendmsg

{    "msg":"hellopeabody",    "username":"peabody"}

python客户端接收到数据

474d87c1e6c04de4bce3dbf9c42c196b

接收到的websocket数据

搭建websocket服务端大致需要以下动作:

  1. 创建一个编程式的端点,需要继承Endpoint类,重写它的方法。
  2. 当创建好一个端点之后,将它以一个指定的URI发布到应用当中,这样远程客户端就能连接上它了。
  3. 创建Session代表着服务端点与远程客户端点的一次会话。
  4. 创建一个容器为每一个连接创建一个EndPoint的实例,需要利用实例变量来保存一些状态信息。
  5. 使用@OnOpen,@OnMessage,@OnClose,@OnError来处理会话
  6. 对接controller层提供restful接口

springboot使用websocket示例

    /**     * 个人信息推送     * @return     */    @RequestMapping(value="/sendmsg",method = {RequestMethod.GET, RequestMethod.POST})    @ResponseBody    public String sendmsg(@RequestBody WebSendMsg webSendMsg){        //第一个参数 :msg 发送的信息内容        //第二个参数为用户长连接传的用户人数        String msg=webSendMsg.getMsg();        String username=webSendMsg.getUsername();        String [] persons = username.split(",");        SocketServer.SendMany(msg,persons);//        特殊字符检测,关闭连接        if ("close()".equals(msg)){            SocketServer.closewebsocket(username);        }        return "success";    }    /**     * 推送给所有在线用户     * @return     */    @RequestMapping("sendAll")    @ResponseBody    public String sendAll(String msg){        SocketServer.sendAll(msg);        return "success";    }
3a62eac64690448bac786c2f85517603

websocket服务