WebSocket
介绍:
WebSocket 是一种网络传输协议,可在单个 TCP 连接上进行全双工通信。它允许服务器主动向客户端推送信息,客户端也能实时接收服务器的响应。
客户端
这里实现了将input内的内容发送给客户端,并将接收到的服务器的消息显示在messages中
<div>
<!-- 接受消息 -->
<ul id="messages"></ul>
<input id="keywords" type="text">
<button id="send">Send</button>
<button id="close">Close</button>
</div>
<script>
const socket = new WebSocket('ws://localhost:9002');
socket.addEventListener("open", function(event) {
console.log('Connected to server');
// socket.send('Hello from client');
});
socket.addEventListener("message", function(event) {
console.log('Received message from server:'+ event.data);
const li = document.createElement('li');
li.textContent = event.data;
messagesList.appendChild(li);
});
socket.addEventListener("close", function(event) {
console.log('Connection closed');
});
// 发消息
const sendBtn = document.getElementById('send');
const closeBtn = document.getElementById('close');
const keywordsInput = document.getElementById('keywords');
const messagesList = document.getElementById('messages');
sendBtn.addEventListener('click', function() {
const message = keywordsInput.value;
const data = JSON.stringify({
user: 'Client1',
message: message
});
socket.send(data);
// const li = document.createElement('li');
// li.textContent = message;
// messagesList.appendChild(li);
keywordsInput.value = '';
});
closeBtn.addEventListener('click', function() {
socket.close();
});
</script>
服务端
这里我自己写了个简单的node服务器来做测试
const http = require('http');
const WebSocketServer = require('ws').Server;
const server = http.createServer();
const wss = new WebSocketServer({ server });
// 接收其他请求
server.on('request', (req, res) => {
res.end('Hello, world!');
});
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (data) => {
console.log(`Received message: ${data}`);
data = JSON.parse(data);
// 实现websocket单发
ws.send(`${data.user}: ${data.message}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
server.listen(9002, () => {
console.log('Server started on port 9002');
});
效果:
有趣的来了,如果你想实现服务器给所有客户端群发消息,类似聊天对话的效果可以这么做:
将
// 实现websocket单发
ws.send(`${data.user}: ${data.message}`);
改为
// 实现websocket群发
wss.clients.forEach(function each(client) {
client.send(`${data.user}: ${data.message}`);
});
聊天对话效果: