您現在的位置是:首頁 > 動作武俠首頁動作武俠

手把手教你建立自己的聊天伺服器,get起來

簡介10:8080websocketsendmsg{“msg”:“hellopeabody”,“username”:“peabody”}python客戶端接收到資料接收到的websocket資料搭建websocket服務端大

如何搭建自己的伺服器

首先說一下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客戶端接收到資料

手把手教你建立自己的聊天伺服器,get起來

接收到的websocket資料

搭建websocket服務端大致需要以下動作:

建立一個程式設計式的端點,需要繼承Endpoint類,重寫它的方法。

當建立好一個端點之後,將它以一個指定的URI釋出到應用當中,這樣遠端客戶端就能連線上它了。

建立Session代表著服務端點與遠端客戶端點的一次會話。

建立一個容器為每一個連線建立一個EndPoint的例項,需要利用例項變數來儲存一些狀態資訊。

使用@OnOpen,@OnMessage,@OnClose,@OnError來處理會話

對接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”; }

手把手教你建立自己的聊天伺服器,get起來

websocket服務

Top