python服务器同web端进行 websocket传输

1.python服务器端:

1)主函数中写入websocket启动 

    t = threading.Thread(target=startWebsocketServer)

    t.start()

2)服务器信息

def startWebsocketServer():

    global server

    def new_client(client, server):

        print(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(port=30031, host='0.0.0.0')

    server.set_fn_new_client(new_client)

    server.set_fn_message_received(mysend)

    server.run_forever()

    server.server_close()

2)服务器发送写法

server.send_message_to_all(disasterInfo)

3.web端接收

    var websocket = null;

    if ('WebSocket' in window) {

      // 获取服务器地址

      websocket = new WebSocket('ws://localhost:30031');

    } else {

      alert("浏览器不支持WebSocket");

    }

    //打开

    websocket.onopen = function (event) {

      console.log('建立连接');

    }

    websocket.onclose = function (event) {

      console.log('连接关闭');

    }

    websocket.onmessage = function (event) {

      console.log(event.data);

//由于只能以字符串形式发送,以;作为分隔,获取对应数据

      var rsArr = event.data.split(";")

      console.log(rsArr);

      if (rsArr[0] == "position") {

       var username = rsArr[1];

        var x = rsArr[2];

        var y = rsArr[3];

        var areaId = rsArr[4];

        var time = rsArr[5];

        console.log(username);

      }

    }

    websocket.onerror = function (event) {

      //alert('通讯错误');

    }

    window.onbeforeunload = function () {

      websocket.close();

    }

你可能感兴趣的:(服务器,python,前端,websocket)