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
相关推荐
不做菜鸟的网工1 天前
BGP特性
网络协议
明月_清风3 天前
开发者网络概念全扫盲:一篇搞定
后端·网络协议
刘马想放假4 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
王二端茶倒水5 天前
一套可落地的无线运营方案,不能只管 AP,还要管用户、计费和运维
网络协议
162723816085 天前
EtherCAT 分布式时钟(DC)原理与配置实战:把多轴真正"对齐到同一时刻"
网络协议
王二端茶倒水5 天前
宽带无线项目,怎么从一次性交付变成长期运营收入?
网络协议
用户2530171996276 天前
第6篇:从技术到产品 — Ghost Proxifier 的设计哲学
网络协议
用户2530171996276 天前
第3篇:注入的艺术 — Ghost Proxifier 核心架构拆解
网络协议
王二端茶倒水8 天前
商业 WiFi 不是免费上网,而是门店数字化的入口
网络协议