您尚未登录,请登录后浏览更多内容! 登录 | 立即注册

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

cncml手绘网 首页 站长博文 学习笔记 查看内容

[php学习资料]浏览器使用WebSocket实时通讯

2019-11-1 11:59| 发布者: admin| 查看: 378| 评论: 0|原作者: admin

摘要: 浏览器使用WebSocket实时通讯

如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接:

  1. <font color="rgb(0, 0, 136)">var</font> socket = <font color="rgb(0, 0, 136)">new</font> WebSocket(<font color="rgb(0, 153, 0)">"ws://172.0.0.1:8080/SpringWebSocketPush/websck"</font>);  
复制代码


与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。


该套接口对象有四个用来监听套接口事件的回调:

  
  1.     socket.onopen = function(){

  2.         //打开

  3.     }


  4.     socket.onmessage = function(){

  5.         //在event.data消息数据

  6.     }

  7.     socket.onclose = function(){

  8.         //关闭WebSocket

  9.     }

  10.     socket.onerror = function(){

  11.         //错误触发

  12.     }
复制代码

通过套接口发送数据,调用socket.send:

  
  1. <font color="rgb(79, 79, 79)">socket</font>.<font color="rgb(79, 79, 79)">send</font>(message)
复制代码


代码附上:

  1. <!DOCTYPE html>
  2. <html>

  3.     <head>
  4.         <meta charset="UTF-8">
  5.         <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
  6.         <title>WebSocket</title>
  7.     </head>

  8.     <body>
  9.     </body>
  10.     <script>
  11.         var socket;
  12.         if (window.WebSocket) {
  13.             socket = new WebSocket("ws://localhost:8080/myapp");
  14.             socket.onmessage = function(event) {
  15.                 alert("Received data from websocket: " + event.data);
  16.             }
  17.             socket.onopen = function(event) {
  18.                 alert("Web Socket opened!");
  19.             };
  20.             socket.onclose = function(event) {
  21.                 alert("Web Socket closed.");
  22.             };
  23.         } else {
  24.             alert("Your browser does not support Websockets. (Use Chrome)");
  25.         }

  26.         function send(message) {
  27.             if (!window.WebSocket) {
  28.                 return;
  29.             }
  30.             if (socket.readyState == WebSocket.OPEN) {
  31.                 socket.send(message);
  32.             } else {
  33.                 alert("The socket is not open.");
  34.             }
  35.         }
  36.     </script>

  37. </html>
复制代码



鲜花

握手

雷人

路过

鸡蛋

最新评论

关闭

站内最热文章上一条 /1 下一条

GMT+8, 2024-4-20 17:45 , Processed in 0.118441 second(s), 25 queries .

Copyright © 2001-2024 Powered by cncml! X3.2. Theme By cncml!