先安装socket.io
npm install socket.io
服务端代码:
let app = require('http').createServer();
let io = require('socket.io')(app, { cors: true });
let port = 3000;
let clientCount = 0;
app.listen(port);
io.on('connection', function (socket) {
clientCount++;
socket.nickname = 'user' + clientCount;
io.emit('enter', socket.nickname + ' comes in');
socket.on('message', function (str) {
io.emit('message', socket.nickname + ' says: ' + str);
})
socket.on('disconnect', function () {
io.emit('leave', socket.nickname + ' left');
})
});
console.log("Websocket server listening on port = " + port)
客户端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocketIO</title>
<script src="https://cdn.socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
<h1>Chat Room</h1>
<input id="sendTxt" type="text" />
<button id="sendBtn">发送</button>
<script type="text/javascript">
let socket = io("ws://localhost:3000/");
function showMessage(str, type){
let div = document.createElement('div');
div.innerHTML = str;
if(type == "enter"){
div.style.color = "blue";
}
else if(type == "leave"){
div.style.color = "red";
}
document.body.appendChild(div);
}
document.getElementById("sendBtn").onclick = function () {
let txt = document.getElementById("sendTxt").value;
if(txt){
console.log(txt)
socket.emit('message', txt);
}
}
socket.on('enter', function (data) {
showMessage(data, 'enter');
})
socket.on('message', function (data) {
showMessage(data, 'message');
})
socket.on('leave', function (data) {
showMessage(data, 'leave');
})
</script>
</body>
</html>
运行截图如下:
退出:
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq78442761/article/details/121351106
内容来源于网络,如有侵权,请联系作者删除!