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
相关推荐
liulilittle1 天前
关于拥塞控制的几点思考
网络·c++·tcp/ip·计算机网络·信息与通信·tcp·通信
AOwhisky1 天前
MySQL 学习笔记(第四期):SQL 语言之多表查询
linux·运维·网络·数据库·笔记·学习·mysql
Phantom Void1 天前
服务器处理客户端请求的设计方法
linux·运维·网络
王码码20351 天前
办了500M宽带看视频还是卡?我用NAS搭了个测速服务器,宽带有没有缩水一测便知
网络·接口·nas
ylscode1 天前
Anthropic Claude Oceanus意外泄露:Mythos系列AI红队测试遭遇API代理滥用危机
网络·人工智能·安全·web安全·安全威胁分析
myenjoy_11 天前
MQTT 与 Sparkplug B——从车间到云端的最后一公里
网络·python
8125035331 天前
第13篇:TCP vs UDP——可靠与速度的博弈
网络协议·tcp/ip·udp
2401_873479401 天前
企业安全运营中,如何用IP离线库提前发现失陷主机?三步实现风险画像
网络·数据库·python·tcp/ip·ip
喵个咪1 天前
实时游戏网络协议深度对比:KCP vs WebRTC vs WebSocket
后端·websocket·webrtc
代码中介商1 天前
HTTP 完全指南(最终篇):CORS 跨域资源共享深度详解
网络·网络协议·http