博客列表 >php实现websocket实时消息推送

php实现websocket实时消息推送

php开发大牛
php开发大牛原创
2018年04月19日 15:35:051157浏览

<!doctype html>

<html lang="en">

 <head>

 <meta charset="UTF-8">

 <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no">

 <title>websocket</title>

 </head>

 <body>

 <input id="text" value="">

 <input type="submit" value="send" onclick="start()">

 <input type="submit" value="close" onclick="close()">

<div id="msg"></div>

 <script>

 /**

 0:未连接

1:连接成功,可通讯

2:正在关闭

3:连接已关闭或无法打开

*/

  //创建一个webSocket 实例

  var webSocket = new WebSocket("ws://192.168.31.152:8083");

  webSocket.onerror = function (event){

    onError(event);

  };

  // 打开websocket

  webSocket.onopen = function (event){

    onOpen(event);

  };

  //监听消息

  webSocket.onmessage = function (event){

    onMessage(event);

  };

  webSocket.onclose = function (event){

    onClose(event);

  }

  //关闭监听websocket

  function onError(event){

    document.getElementById("msg").innerHTML = "<p>close</p>";

    console.log("error"+event.data);

  };

  function onOpen(event){

    console.log("open:"+sockState());

    document.getElementById("msg").innerHTML = "<p>Connect to Service</p>";

  };

  function onMessage(event){

    console.log("onMessage");

    document.getElementById("msg").innerHTML += "<p>response:"+event.data+"</p>"

  };

  function onClose(event){

    document.getElementById("msg").innerHTML = "<p>close</p>";

    console.log("close:"+sockState());

    webSocket.close();

  }

  function sockState(){

    var status = ['未连接','连接成功,可通讯','正在关闭','连接已关闭或无法打开'];

      return status[webSocket.readyState];

  }

 function start(event){

    console.log(webSocket);

    var msg = document.getElementById('text').value;

    document.getElementById('text').value = '';

    console.log("send:"+sockState());

    console.log("msg="+msg);

    webSocket.send("msg="+msg);

    document.getElementById("msg").innerHTML += "<p>request"+msg+"</p>"

  };

  function close(event){

    webSocket.close();

  }

 </script>

 </body>

</html>


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议