Node.js环境WebSocket示例

server.js:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 3000 });

wss.on('connection', function connection(ws) {
  console.log('客户端已连接');

  ws.on('message', function incoming(message) {
    console.log('收到客户端消息:', message);
    ws.send(`服务端收到消息: ${message}`);
  });

  ws.on('close', function close() {
    console.log('客户端已断开连接');
  });
});

client.js:

const WebSocket = require('ws');

const clientSocket = new WebSocket('ws://localhost:3000');

clientSocket.on('open', function open() {
  console.log('连接已建立');
  clientSocket.send('Hello, WebSocket Server from Client!');
});

clientSocket.on('message', function incoming(data) {
  console.log('收到服务端消息:', data);
});

clientSocket.on('close', function close() {
  console.log('连接已关闭');
});

这里直接用ws模块提供的WebSocket来充当客户端,如果报错,试着升级下ws包。

相关推荐

  1. Node.js环境WebSocket示例

    2024-04-15 08:12:02       18 阅读
  2. websocket 前端项目js示例

    2024-04-15 08:12:02       9 阅读
  3. springboot webscoket示例:增加定时心跳逻辑

    2024-04-15 08:12:02       17 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-15 08:12:02       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-15 08:12:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-15 08:12:02       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-15 08:12:02       20 阅读

热门阅读

  1. 顺序表原码(练习版)

    2024-04-15 08:12:02       18 阅读
  2. ES6 的解构赋值

    2024-04-15 08:12:02       18 阅读
  3. 浏览器从输入url到渲染的过程

    2024-04-15 08:12:02       17 阅读
  4. CentOS 设置静态 IP 配置

    2024-04-15 08:12:02       48 阅读
  5. TCP 粘包

    2024-04-15 08:12:02       45 阅读
  6. 免费GPT-3.5部署指南

    2024-04-15 08:12:02       17 阅读
  7. 安装spdlog

    2024-04-15 08:12:02       15 阅读
  8. 【Windows】如何在Windows系统上用Sudo

    2024-04-15 08:12:02       51 阅读
  9. PL/SQL与SQL的区别:从结构化查询到过程化编程

    2024-04-15 08:12:02       45 阅读
  10. TCP的三次握手

    2024-04-15 08:12:02       18 阅读
  11. 【CSS】CSS水平居中方案

    2024-04-15 08:12:02       15 阅读