Implementing a group chat room using socket.io
This article will share with you an example of using socket.io to realize the function of group chat. If you want to use socket.io, you must use nodejs to implement the server, so we need to install socket.io in nodejs
Install socket.io
How to install socket.io in nodejs? For those who have just started learning nodejs, there may be some problems. Completing a nodejs project requires two parts, one is the installation directory of the nodejs tool, which is equivalent to the PHP parser, and the other is the nodejs code part. Socket.io can be said to be a toolkit of nodejs. If we have learned PHP, then if we need to use the extension tools in PHP, we need to recompile the PHP parser. But for nodejs, its third-party tools must be installed in the nodejs code part. We can use the following figure for comparison
Then let's introduce our directory structure.
First, our nodejs environment is in the root directory
/nodejs
Then our project directory
/www/nodejs
Next, we enter the project directory
# cd /www/nodejs
Then use the npm command under /nodejs/bin to install socket.io to the project directory
nodejs]# /nodejs/bin/npm install socket.io
After the installation is complete, we can create a new js file under the project directory, named socketserver.js
socketserver.js
var http = require('http').createServer(handle);
var io = require('socket.io')(http);
var url = require('url');
var files = require('fs');
http.listen(9999,"192.168.144.128");//监听9999端口
function handle(req,res){
files.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
var onlineUsers = {};
//当前在线人数
var onlineCount = 0;
/**
* 用户连接
*/
io.on('connection',function(socket){
/**
* 监听新用户加入
*/
socket.on('login',function(obj){
io.emit('login',{username:obj.username});
onlineCount++
});
/**
* 发布消息
*/
socket.on('message',function(obj){
io.emit('message',{username:obj.username,userid:obj.userid,message:obj.message});
});
/**
* 上传文件
*/
socket.on('upfile',function(obj){
var dir = __dirname.substr(0,__dirname.lastIndexOf('module'));
var file = dir+"data/Upload/"+obj.filename;
files.open(file,'w',function(err,fd){
if(!err){
var option ={
flags: 'w',
encoding: null,
fd: fd,
mode: 0666
};
var ws = files.createWriteStream(file,option);
ws.write(obj.message);
io.emit('upfile',{username:obj.username,userid:obj.userid,message:"/data/Upload/"+obj.filename});
}
});
console.log(dir);
});
});
上面是服务端代码
接下来完成客户端的代码
chatclient.js
var CHAT = {
username:null,
userid: null,
message:null,
}
var socket = io.connect('ws://192.168.144.128:9999');
socket.on('login',function(obj){
var con = $('#chat_show .show_message').html()+"<br />"+obj.username+'---joined';
$('#chat_show .show_message').html(con);
});
socket.on('message',function(obj){
var info = '';
if(CHAT.userid == obj.userid){
info = "<span style='display:block;width:100%;text-align:right;'>"+obj.username+': '+obj.message+"</span>";
}else{
info = "<span style='display:block;width:100%;text-align:left;'>"+obj.username+': '+obj.message+"</span>";
}
var con = $('#chat_show .show_message').html()+info;
$('#chat_show .show_message').html(con);
});
socket.on('upfile',function(obj){
var info = '';
if(CHAT.userid == obj.userid){
info = "<span style='display:block;width:100%;text-align:right;'>"+obj.username+":<img src='"+obj.message+"' width='100' height='100' /></span>";
}else{
info = "<span style='display:block;width:100%;text-align:left;'>"+obj.username+": <img src='"+obj.message+"' width='100' height='100' /></span>";
}
var con = $('#chat_show .show_message').html()+info;
$('#chat_show .show_message').html(con);
});
socket.emit('login',{username:CHAT.username});
以上是客户端的核心代码
综合以上的代码,有两个知识点需要注意。
一是 socket.on(“事件名称”,function(){处理代码})。不管是在服务端还是在客户端,这是在socket上开启一个方法,进行监听,一旦有数据向这个方法发送数据,就会调用后面的function()进行处理。
那如何向这个事件发送数据,那就需要用到 socket.emit(“事件名称”,数据);来向对方发送数据,双方的事件名称是相互对应的。客户端的emit-事件名称对应服务端的 on-事件名称;服务端的emit-事件名称对应于客户端的on-事件名称。
如此我们就完成了群聊天的功能,当然上述代码是不完整的,不过核心的代码都在上面,缺少的就是页面了。大家可以根据上面的代码自行进行扩展,制作出更强大的网页聊天室。如果有什么问题请在下面留言讨论,大家共同提高
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Article URL:https://www.jiyik.com/en/xwzj/network_9826.html
Related Articles
What multipart/form-data does in post Upload upload files
Publish Date:2025/03/18 Views:63 Category:NETWORK
-
Everyone has used the attribute enctype="multipart/form-data" when uploading files using a form. What is the role of multipart/form-data? Let's talk about this topic. First, let's look at a case Look at the first code form action= "handl
About application/x-www-form-urlencoded
Publish Date:2025/03/18 Views:147 Category:NETWORK
-
As a data format of form, application/x-www-form-urlencoded has its own characteristics form action= "handle.php" method= "post" input type= "text" name= " uname" class= " uname" /br / input type= "text" name= "email" class=
My understanding of webservice is this
Publish Date:2025/03/18 Views:147 Category:NETWORK
-
Recently, I encountered such a project at work (temporarily named Project A). Project A itself was developed in PHP, but its data came from another project developed in Java (temporarily named Project B). Project A could not operate the dat
WSDL looks like this
Publish Date:2025/03/18 Views:190 Category:NETWORK
-
When I first started learning Webservice, I found that there were quite a lot of knowledge points involved, and each point could be a school of its own. Especially when I saw WSDL, I looked up information for a long time, but I was still a
Which technology do you choose to implement the web chat room?
Publish Date:2025/03/18 Views:61 Category:NETWORK
-
With the rise of HTML5 Websockets, web chat applications are becoming more and more popular. Recently, I am working on a mobile web application, the core function of which is to implement web chat on the mobile phone. Of course, the functio
Getting started with FastCGI
Publish Date:2025/03/18 Views:164 Category:NETWORK
-
In "First Contact with CGI", we mentioned the operating mechanisms of CGI and Server APIs, as well as their respective advantages and disadvantages. In this chapter, we will learn about FastCGI, which combines the advantages of CGI and Serv
Build the SVN service project and synchronize the code to the project directory
Publish Date:2025/03/18 Views:197 Category:NETWORK
-
As the project grows, more people are needed to participate in the development of the same project. SVN is used for multiple people to jointly develop the same project and share resources. There are two ways to run SVN server: one is as a s
Ajax cross-domain cookie related settings
Publish Date:2025/03/18 Views:87 Category:NETWORK
-
In web programming, we often encounter cross-domain issues. By default, browsers do not allow cross-domain access. Therefore, there is a concept here: CORS (Cross-Origin Resource Sharing). Before the HTML5 standard came out, CORS was not al
PHP+ajax to achieve cross-domain single sign-on
Publish Date:2025/03/16 Views:145 Category:NETWORK
-
We have previously introduced the principle of cross-domain single sign-on in "Detailed explanation of the implementation methods of three situations of SSO single sign-on" . Here we will introduce how to implement single sign-on using PHP