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