TOC
展示
代码
两份文件,client server
//test.html
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.bootcss.com/socket.io/2.0.3/socket.io.js"></script>
</head>
<body>
<input type="text" id="input">
<button id="sendMess">send</button>
</body>
<script type="text/javascript">
let socket = io("ws://localhost:4500/")
//show APi
function showMessage(str,type){
let box = document.createElement("div")
box.innerHTML = str
if(type === "enter"){
box.style.color = "#33B5FF";
}else if(type === "leave"){
box.style.color === "red"
}else{
box.style.color = "#333"
}
document.body.appendChild(box)
}
//io
document.getElementById("sendMess").onclick=function(){
let str = document.getElementById("input").value
if(str){
socket.emit("message",str)
document.getElementById("input").value = ""
}
}
socket.on("enter",(data)=>{
showMessage(data,"enter")
})
socket.on("leave",(data)=>{
showMessage(data,"leave")
})
socket.on("message",(data)=>{
showMessage(data,"message")
})
</script>
</html>
server
const app = require('http').createServer()
const io = require('socket.io')(app)
let clientId = 0
let port = 4500
app.listen(port)
//每当新用户链接,就创建进行初始化及回调绑定
io.on('connection', function (socket) {
//为每个用户分配ID
clientId++
socket.nickname = "user ID" + clientId
//向所有目标发送连接消息
io.emit('enter', socket.nickname + " is enter")
socket.on("message", (str) => {
io.emit("message",socket.nickname +" say:" + str)
})
socket.on('disconnect', (str) => {
io.emit("leave",socket.nickname + "is leave")
})
})
console.log("ws server listing on port " + port + "....");
我们可以看到在非常少量代码的情况下就可以处理一个IM的系统,这可都得仰仗socket.io.
对于socket.io我最大的的一个体会就是emit和on非常直接,简洁,你可以像阅读自然语言一样把他直接给读出来。第二点是可以直接传播对象,他帮你做一个对象的转换。第三是利用io可以及其方便的对每个客户端传播消息,你无须自己手动遍历客户端列表
地址
项目地址: https://github.com/zhangzhengyi12/websocket-im-demo