python实现WebsocketServer 服务端

python 实现weisocket服务端用到的库为:websocket-server 0.4  :

https://pypi.org/project/websocket-server/0.4/

https://github.com/Pithikos/python-websocket-server

服务端代码:

#coding:utf-8

from lib.socket.websocket_server import WebsocketServer


def startWebsocketServer():
    def new_client(client, server):
        server.send_message_to_all("Hey all, a new client has joined us")

    def mysend(client,server,msg):
        print(msg)
        server.send_message(client,"哈哈哈哈哈")
        if(msg == "_end"):         #如果收到了_end 消息,那么断开连接
            server.server_close()

    server = WebsocketServer(5005, host='127.0.0.1', loglevel=logging.INFO)
    server.set_fn_new_client(new_client)
    server.set_fn_message_received(mysend)
    server.run_forever()
    server.server_close()

if __name__ == "__main__":
    startWebsocketServer()

网页端代码:



   
   
   websocket测试
    
  
        
   
   
   
      

 

你可能感兴趣的:(Python,JavaScript)