Nodejs实现多房间简易聊天室功能

2020-06-17 06:17:05易采站长站整理

1、前端界面代码

  前端不是重点,够用就行,下面是前端界面,具体代码可到github下载。

2、服务器端搭建

  本服务器需要提供两个功能:http服务和websocket服务,由于node的事件驱动机制,可将两种服务搭建在同一个端口下。

  1、包描述文件:package.json,这里用到了两个依赖项,mime:确定静态文件mime类型,socket.io:搭建websocket服务,然后使用npm install  安装依赖


{
"name": "chat_room",
"version": "1.0.0",
"description": "this is a room where you can chat with your friends",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "sfs",
"license": "ISC",
"dependencies": {
"socket.io":"2.0.3",
"mime":"1.3.6"
}
}

  2、http服务器

  http服务主要是给web浏览器提供静态文件,既浏览器发来一个请求,服务器返回一个响应。


const
http=require('http'),
fs=require('fs'),
path=require('path'),
mime=require('mime'),
chatServer=require('./lib/chat_server');

var cache={};//缓存静态文件内容
//发送错误响应
function send404(response){
response.writeHead(404,{'Content-Type':'text/plain'});
response.write('Error 4.4:文件未找到。');
response.end();
}
//发送文件内容
function sendFile(response,filePath,fileContents){
response.writeHead(
200,
{"content-Type":mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
//查找文件
function serveStatic(response,cache,absPath){
if(cache[absPath]){
sendFile(response,absPath,cache[absPath]);
}else{
fs.exists(absPath,function(exists){
if(exists){
fs.readFile(absPath,function(err,data){
if(err){
send404(response);
}else{
cache[absPath]=data;
sendFile(response,absPath,data);
}
});
}else{
send404(response);
}
});
}
}
//入口
var server=http.createServer(function(request,response){
var filePath=false;
console.log(`new request for ${request.url}`);
if(request.url==='/'){
filePath='public/index.html';
}else{
filePath='public'+request.url;
}

var absPath='./'+filePath;
serveStatic(response,cache,absPath);
});
server.listen(3000,function(){
console.log("the server is listening on prot 3000.");
});
chatServer.listen(server); //websocket服务也绑定到该端口上

  3、socket服务

  socket.io提供了开箱既用的虚拟通道,所以不需要任务手动转发消息到已连接的的用户,可以使用 socket.broadcast.to(room).emit(‘message’,’hello’); room为某个聊天室id