python WebsocketServerサービスを実現

2133 ワード

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()

Web側コード:


   
   
   websocket  
    
  
	 ws = null;
	 i = 1;

	 (function(){
		ws = null;
		i = 1;
	 })()

	 function WebSocketTest()
	 {
		if ("WebSocket" in window)
		{
		   console.log("        WebSocket!");
		   
		   ws = new WebSocket("ws://127.0.0.1:5005");
			
		   ws.onopen = function()
		   {
			  // Web Socket     ,   send()       
			  //ws.send("hello world !");
			  console.log("socket      !")
		   };
			
		   ws.onmessage = function (evt) 
		   { 
			  var received_msg = evt.data;
			  console.log(evt.data)
		   };
			
		   ws.onclose = function()
		   { 
			  //    websocket
			  alert("     ..."); 
		   };
		}
		else
		{
		   //        WebSocket
		   console.log("         WebSocket!");
		}
	 }
   
   function sendMsg(){
		ws.send("hello world" + i++);
   }

   function myclose(){
		ws.send("_end");
		ws.close()
		console.log("       ...")
   }