webSocket Demo1

package.json

json 复制代码
{
  "name": "websocket-demo",
  "version": "1.0.0",
  "description": "WebSocket Demo",
  "main": "server.js",
  "scripts": {
    "dev": "node server.js"
  },
  "dependencies": {
    "ws": "^8.14.2"
  },
  "keywords": [
    "websocket"
  ],
  "author": "monkey",
  "license": "MIT"
}

index.html

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket</title>
  </head>
  <body>
    <button onclick="sendMsg()">发送消息</button>
  </body>
  <script>
  const socket = new WebSocket('ws://127.0.0.1:9000');

  socket.onopen = function (e) {
    console.log('页面连接成功');
  };

  socket.onmessage = function (e) {
    console.log('页面收到消息', e.data);
  };

  socket.onclose = function (e) {
    console.log('页面连接关闭');
  };

  socket.onerror = function (e) {
    console.error(e);
  };

  function sendMsg() {
    socket.send('hello world');
  }
  </script>
</html>

server.js

javascript 复制代码
const http = require('http');
const webSocket = require('ws');

const server = http.createServer();

const wss = new webSocket.Server({ server });

wss.on('connection', function connection(ws) {

  ws.on('message', function incoming(message) {
    console.log('收到消息: %s', message);
    // 发送消息
    ws.send('something');
  });

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

server.listen(9000, function listening() {
  console.log('启动成功, 端口号: 9000');
});

启动命令

1. 安装依赖

bash 复制代码
npm install

2. 启动服务

bash 复制代码
npm run dev
相关推荐
聚铭网络5 小时前
聚铭网络成功入围徐州市大数据集团2026年业务类合作供应商名录(第一批次)
大数据·网络
hy____1236 小时前
Linux_网络基础3
linux·服务器·网络
Striver-Diligent7 小时前
GenNP: 一种低门槛且功能强大的网络性能数据生成器
网络·计算机网络·并行·网络仿真·网络性能估计·离散事件仿真
带娃的IT创业者7 小时前
Weclaw 请求路由实战:一个 request_id 如何在 800 个并发连接中精准找到目标浏览器?
python·websocket·fastapi·架构设计·实时通信·openclaw·weclaw
望未来无悔8 小时前
实时传输的选择方案
websocket
我是唐青枫10 小时前
C#.NET ReadOnlySequence 深入解析:多段内存遍历与零拷贝协议解析
网络·c#·.net
带娃的IT创业者11 小时前
WeClaw 心跳与重连实战:指数退避算法如何让 WebSocket 在弱网环境下的连接成功率提升 67%?
python·websocket·网络协议·算法·fastapi·实时通信
Insist75312 小时前
案例二---集群修改物理IP和VIP
运维·网络·数据库
qq_4112624212 小时前
在建立udp连接的时候,有时候能成功,有时候AT 指令返回+ERRNO:0x70
网络·网络协议·udp
专家大圣13 小时前
告别智能家居品牌壁垒✨ Home Assistant+cpolar 让远程控家更省心
网络·docker·智能家居·内网穿透·cpolar