• nodejs+expressjs+ws实现了websocket即时通讯,服务器和客户端互相通信


    nodejs代码

    // 导入WebSocket模块:
    const WebSocket = require('ws');

    // 引用Server类:
    const WebSocketServer = WebSocket.Server;

    // 实例化:
    const wss = new WebSocketServer({
      port: 3001
    });
    wss.on('connection', function (ws) {
      console.log(`ws 已经连接上`);
      ws.on('message', function (message) {

        console.log(`收到客户端的数据: ${message}`);
        ws.send(`服务端接收到数据,给客户端返回数据: ${message}`, (err) => {
          if (err) {
            console.log(`[SERVER] error: ${err}`);
          }
        });
      })
    });
    2. html代码
          // 打开一个WebSocket:
          var ws = new WebSocket('ws://localhost:3001');
         
          // 响应onmessage事件:
          ws.onmessage = function (msg) { console.log(msg); };
         
          // 给服务器发送一个字符串:
          ws.addEventListener('open', function () {
            let msg = '我是客户端: ' + location.href
              ws.send(msg)
          });
    3. 当然  必须提前导入ws模块  npm i ws
  • 相关阅读:
    Design Pattern
    javascript summary
    nodejs template
    MVC---Case 1
    About js
    本地schemeApp扩展
    BNU4208:Bubble sort
    [置顶] think in java interview-高级开发人员面试宝典代码示例
    java+socket 简易聊天工具
    oracle 字段自增 两段代码搞定
  • 原文地址:https://www.cnblogs.com/cengjingdeshuige/p/10259349.html
Copyright © 2020-2023  润新知