加入收藏 | 设为首页 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > 学习资料

浏览器使用WebSocket实时通讯

时间:2021-03-22 00:11:34  来源:  作者:

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

  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:// 前缀。


该套接口对象有四个用来监听套接口事件的回调:
Kku华陈数据科技

  
  1.     socket.onopen = function(){
  2.  
  3.         //打开
  4.  
  5.     }
  6.  
  7.  
  8.     socket.onmessage = function(){
  9.  
  10.         //在event.data消息数据
  11.  
  12.     }
  13.  
  14.     socket.onclose = function(){
  15.  
  16.         //关闭WebSocket
  17.  
  18.     }
  19.  
  20.     socket.onerror = function(){
  21.  
  22.         //错误触发
  23.  
  24.     }
复制代码
 

通过套接口发送数据,调用socket.send:Kku华陈数据科技

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

代码附上:Kku华陈数据科技

  1. <!DOCTYPE html>
  2. <html>
  3.  
  4.     <head>
  5.         <meta charset="UTF-8">
  6.         <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
  7.         <title>WebSocket</title>
  8.     </head>
  9.  
  10.     <body>
  11.     </body>
  12.     <script>
  13.         var socket;
  14.         if (window.WebSocket) {
  15.             socket = new WebSocket("ws://localhost:8080/myapp");
  16.             socket.onmessage = function(event) {
  17.                 alert("Received data from websocket: " + event.data);
  18.             }
  19.             socket.onopen = function(event) {
  20.                 alert("Web Socket opened!");
  21.             };
  22.             socket.onclose = function(event) {
  23.                 alert("Web Socket closed.");
  24.             };
  25.         } else {
  26.             alert("Your browser does not support Websockets. (Use Chrome)");
  27.         }
  28.  
  29.         function send(message) {
  30.             if (!window.WebSocket) {
  31.                 return;
  32.             }
  33.             if (socket.readyState == WebSocket.OPEN) {
  34.                 socket.send(message);
  35.             } else {
  36.                 alert("The socket is not open.");
  37.             }
  38.         }
  39.     </script>
  40.  
  41. </html>
复制代码

 
 
 
 
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
实现php间隔一段时间执行一次某段代码
实现php间隔一段时间
相关文章
    无相关信息
栏目更新
栏目热门