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
相关推荐
白毛大侠6 小时前
理解 Go 接口:eface 与 iface 的区别及动态性解析
开发语言·网络·golang
萌萌哒草头将军10 小时前
CloudDock(云仓):新一代开源NAS网络代理工具
服务器·网络协议·docker
黄筱筱筱筱筱筱筱10 小时前
HCIA网络设备管理
网络
s19134838482d11 小时前
vlan实验报告
运维·服务器·网络
2601_9495394513 小时前
家用新能源 SUV 核心技术科普:后排娱乐、空间工程与混动可靠性解析
大数据·网络·人工智能·算法·机器学习
南湖北漠13 小时前
奇奇怪怪漫画里面的蛞蝓是带壳的那种鼻涕虫
网络·人工智能·计算机网络·其他·安全·生活
ofoxcoding13 小时前
GPT-5.4 vs Claude Opus 4.6 实测对比:2026 年该选哪个模型写代码?
网络·gpt·ai
Agent产品评测局13 小时前
企业发票管理自动化落地,验真归档全流程实现方法:2026企业级智能体选型与实测指南
运维·网络·人工智能·ai·chatgpt·自动化
OPHKVPS13 小时前
WebRAT恶意软件借GitHub伪造漏洞利用程序传播
网络·安全·github
攻城狮在此16 小时前
网络拓扑图绘制规范与实操指南
网络