socket.io需要在服务端和客户端都引入,官网:https://socket.io/
1.目录结构
- socketioChatRoom
- index.html(客户端)
- wsServer.js(服务端)
- socket.io.js(客户端要引入的js:https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js)
2.安装socket.io(https://socket.io/docs/)
- npm install socket.io
3.index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>websocket聊天室</title>
<script src="socket.io.js"></script>
</head>
<body>
<input id="sendTxt" type="text">
<button id="send">send</button>
<script type="text/javascript">
var socket = io("ws://localhost:3000/");
document.getElementById("send").onclick = function() {
var txt = document.getElementById("sendTxt").value;
if (txt) {
socket.emit('message', txt);
}
}
// 显示消息函数
function showMessage(str, type) {
var div = document.createElement('div');
if (type == "enter") {
div.style.color = "red";
} else if (type == "message") {
div.style.color = "blue";
} else if (type == "leave") {
div.style.color = "green";
}
div.innerHTML = str;
document.body.appendChild(div);
}
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>
4.wsServer.js
// 创建一个node的http服务
var app = require('http').createServer();
var io = require('socket.io')(app);
const PORT = 3000;
app.listen(PORT);
// 每进来一个客户端就记录一下
var clientCount = 0;
io.on('connection', function(socket) {
clientCount++;
socket.nickname = 'user' + clientCount;
// socket.io的广播用io对象emit就能实现
io.emit('enter', socket.nickname + ' comes in');
socket.on('message', function(str) {
io.emit('message', socket.nickname + ' says: ' + str);
});
// socket有一个关闭连接的事件类型
socket.on('disconnect', function() {
io.emit('leave', socket.nickname + ' left');
});
});
console.log("websocket server running on port: " + PORT);
5.总结
可以发现基于socket.io的聊天室代码比nodejs-websocket精简多了,而且可以传入对象作为参数,还能自定义事件类型。