Home >Web Front-end >JS Tutorial >Detailed explanation of node.js + socket.io implementing chat function
This article mainly introduces node.js + socket.io to implement point-to-point random matching chat, which has certain reference value. Interested friends can refer to it
Sincerely I admire those who can often post notes. In fact, I also want to send them often. However, I am not skilled enough and am lazy. I need to learn more from the masters. Some time ago, I used the socket that comes with the bomb platform to write a chat room. In fact, it is basically I changed its demo. This time I wanted to implement a random private chat, so I built the service based on node and socket.io. Of course, this is my first time using node to make something. Although I didn’t do it well, I still want to share it. ha.
Let’s first talk about the things used. node is used for background services, express is used to host static resources, and socket.io is used to transmit chat data. Next, let’s talk about the idea. In fact, it is very simple to use socket.io to transmit data. We only need to introduce socket.io.js on the front-end page and then do it on the node side. require('socket. io'), run it on the backend, then the frontend can send or receive information through the following code.
//前端 socket = io.connect('ws://'+'服务器ip'); socket.emit('msg',{msg:'前端要发送的信息'});//要发送的信息(以对象的形式发送) socket.on('msg2',function(data){ ... //这里的data是后端传过来的信息 }) //后端 socket.on('msg',function(data){ var data = data; //这里的data就是前端传过来的数据,即{msg:'前端要发送的信息'} console.log(data.msg) // 打印出 “前端要发送的信息” }) //同理,后端要传信息给前端也是一样 socket.emit('msg2',{msg:'后端要发送的信息'});
Let’s see how the backend runs the socket
var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); io.on('connection', function(socket){ //当前端执行 socket = io.connect('ws://'+host); 的时候,此处的io会监听到connection事件 socket.on('msg',function(data){ io.emit('onlineCount',freeList) //如果直接用io.emit来发送数据的话,这代表广播的形式,就是当前所有打开服务的前端页面都会收到这条消息。 socket.emit('welcome',{msg:'欢迎...'})//这里将给当前连接的页面发送一个欢迎的对象数据 }) socket.on('disconnect',function(){ //当前端页面关闭,或者失去连接时,后端会接收到disconnect事件 }) }) http.listen(4000, function(){ console.log('listening on *:4000'); });
Of course it’s not just that, because of the websocket protocol, A long link is established between the browser and the server to transmit data to each other. For the server, if several pages are opened, there will be several socket instances. Each front-end page that establishes a connection will have a socket instance. , which provides ideas for the subsequent peer-to-peer private chat. Of course, we can also send information via direct broadcast, but this is suitable for chat room scenarios.
How to implement point-to-point? As mentioned before, each page that establishes a connection will generate a socket instance, so we only need the backend to judge while receiving the message Whichever instance the socket instance is chatting with, just send the message to another matching socket instance. To put it simply, it's like writing a letter. I send the message to the backend, and then tell the backend that the message is for xxx. Then the backend finds the socket instance corresponding to xxx and sends the message to him.
//前端 window.id = new Date().getTime()+""+Math.floor(Math.random()*899+100); //每次登录,获取一个唯一的用户id socket = io.connect('ws://'+host); socket.emit('newUser',{ user_name : name, user_id : id}) //建立连接后,将我的用户名和id都传给后端 //后端 socket.on('newUser',function(data){ var nickname = data.user_name, user_id = data.user_id; userServer[user_id] = socket; //后端接收后,将该用户socket保存在一个对象里,key值为id,value就是这个用户的socket })
Through the above code, the backend gets a userServer object, which contains the corresponding value of each connection socket and its id. In this way, you can Point-to-point data transmission is achieved by attaching the ID of the object to be received each time a message is sent.
The next step is data processing, how to get the other party’s ID, etc. In view of my limited expression ability and laziness, I won’t go into details~~ I host the code on github. Welcome yourself. Come down and take a look
The above is the detailed content of Detailed explanation of node.js + socket.io implementing chat function. For more information, please follow other related articles on the PHP Chinese website!