zoukankan      html  css  js  c++  java
  • 前端页面与Nodejs使用websocket通信

    不要用浏览去直接去访问websocket的地址!!!

    不要用浏览去直接去访问websocket的地址!!!

    不要用浏览去直接去访问websocket的地址!!!

    太傻了。。。

    就是页面和服务端有个隐藏的通信而已。

    前端

    1、实例化一个ws对象

    var wsUri ="ws://echo.websocket.org/";
    websocket = new WebSocket(wsUri);

    2、WebSocket对象一共支持四个消息 onopen, onmessage, onclose和onerror,都是事件触发,不会阻塞

    //成功连接后
    websocket.onopen = function(evt) {};
    
    //连接失败
    websocket.onerror = function(evt) { };
    
    //收到信息后
    websocket.onmessage = function(evt) { };
    
    //后端关闭ws的时候
    websocket.onclose = function(evt) { };

    后端

    minicap例程里面是用的ws模块

    注意,ws的所有操作,都要在connection的回调里面执行

    一个例子

    后端每隔1.5s给前端发count++;

    前端收到后打印出来并返给后端收到了什么

    收到了

    服务器代码

    ws_base.js

    只需要启动ws就可以了,不需要绑定服务器

    //获取websocket模块
    const websocket = require('ws').Server;
    
    const wsServer = new websocket({port:8081});
    
    //与wsServer相关的操作,都必须在connection函数里面操作
    //连接成功后会返回一个ws
    wsServer.on('connection',(ws)=>{
    
        let count = 0;
    
        ws.on('message',(message)=>{
            console.log(message);
        });
    
        setInterval(()=>{
            ws.send(count++);
        },1500)
    
    });

    前端代码:

    ws_front.html

    <html>
    <head>
        <title>Ws Demo</title>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
    </head>
    
    <body>
    
        <div>
            <h1 id="show"></h1>
        </div>
    
    
        <script>
        
            const ws = new WebSocket('ws://localhost:8081');
    
            ws.onopen = ()=>{console.log('connect success!');}
    
            ws.onmessage = (message)=>{
                console.log(message);
                ws.send('收到'+message.data);
            }
                
            
        
        </script>
    
    </body>
    
    
    </html>
  • 相关阅读:
    Leetcode Plus One
    Leetcode Swap Nodes in Pairs
    Leetcode Remove Nth Node From End of List
    leetcode Remove Duplicates from Sorted Array
    leetcode Remove Element
    leetcode Container With Most Water
    leetcode String to Integer (atoi)
    leetcode Palindrome Number
    leetcode Roman to Integer
    leetcode ZigZag Conversion
  • 原文地址:https://www.cnblogs.com/weizhibin1996/p/9328650.html
Copyright © 2011-2022 走看看