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
相关推荐
意法半导体STM321 小时前
【官方原创】使用GPDMA进行SPI LCD整屏传输 LAT1435
网络·stm32·单片机·嵌入式硬件·mcu·网络协议·stm32开发
biubiubiu07062 小时前
Certbot 申请SSL证书的三种方式详解(Ubuntu 22.04环境)
网络·网络协议·ssl
budingxiaomoli2 小时前
TCP协议和UDP协议
网络·网络协议·udp
2401_865854882 小时前
兔唧内网文件快传是什么 怎么用?快传使用教程
网络
古译汉书2 小时前
【IoT死磕系列】Day 6:工业控制底层大动脉—CAN总线
linux·网络·arm开发·单片机·物联网·tcp/ip
SamtecChina20232 小时前
Samtec连接器设计研究 | 载流量:温升为什么重要?
大数据·网络·人工智能·算法·计算机外设
打码人的日常分享3 小时前
双碳智慧园区建设方案(PPT)
大数据·运维·网络·云计算·制造
漫霂3 小时前
WebSocket入门
后端·websocket
笨蛋不要掉眼泪3 小时前
Spring Cloud Gateway 核心篇:深入解析过滤器(Filter)机制与实战
java·服务器·网络·后端·微服务·gateway