步骤
- 选择一个WebSocket服务器,这里选择到的模块是ws模块
npm i ws
- 创建一个 WebSocket 服务器 新建一个 server.js 编写如下代码
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
wss.on('connection', (socket) => {
console.log('Client connected');
socket.on('message', (message) => {
console.log(`Received message: ${message}`);
// 回复消息
const reply = `You said: ${message}`;
socket.send(reply);
});
socket.on('close', () => {
console.log('Client disconnected');
});
});
- 这时候我们需要一个页面进行发送消息,所以新建一个index.html代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Chat</title>
</head>
<body>
<div id="messages"></div>
<form id="message-form">
<input type="text" id="message-input">
<button type="submit">Send</button>
</form>
<script>
const socket = new WebSocket('ws://localhost:3000');
let flag = false
socket.addEventListener('open', (event) => {
console.log('Connected to WebSocket server');
});
socket.addEventListener('message', (event) => {
if(flag) { // 是我方的话不走以下
flag = false
return
}
const message = event.data
if (message instanceof Blob) {
const reader = new FileReader();
reader.readAsText(message);
reader.onload = () => {
const text = reader.result;
displayMessage(text, '对方');
};
} else {
displayMessage(message);
}
})
socket.addEventListener('close', (event) => {
console.log('Disconnected from WebSocket server');
});
const form = document.getElementById('message-form');
const input = document.getElementById('message-input');
const messages = document.getElementById('messages');
form.addEventListener('submit', (event) => {
event.preventDefault();
const message = input.value;
input.value = ''
flag = true
socket.send(message);
displayMessage(message, '我');
});
function displayMessage(message, name) {
const p = document.createElement('p');
p.textContent = name+': '+message;
messages.appendChild(p);
}
</script>
</body>
</html>
标签:const,socket,console,对话,简单,WebSocket,message,event From: https://www.cnblogs.com/dcyd/p/17468315.html这个HTML页面包含了一个消息输入框和一个发送按钮,当用户在输入框中输入消息并点击发送按钮时,会将消息发送到WebSocket服务器,并将其显示在页面上
通过socket.send
来发送消息、通过socket.addEventListener
来监听页面收到的消息、通过displayMessage
函数来将消息显示在页面上
用nodejs
来启动server.js
如下node serve.js
在单独打开两个index.html
就能进行对话了