基於nodejs、socket.io簡單的聊天室

項目介紹

該聊天室基於socket.io實現客戶端與服務器雙工實時通訊。該聊天室能夠發送消息、圖片、文件。node

通訊圖

在這裏插入圖片描述

  1. 客戶端與服務器鏈接
  2. 客戶端向服務器發送事件
  3. 服務器接受事件,將事件發送給全部客戶端。實現事件廣播。

客戶端git

1.  建立客戶端並鏈接服務器 localhost:3000
    

 var socket = io('localhost:3000')

2.  向服務器發送事件
    

 //發送用戶名  
 socket.emit("join", name)  
 //發送消息  
 socket.emit("message", userObj)   
 //發送文件、圖片  
 socket.emit('base64 file', msg);

3.  監聽服務器發來的事件
    

 socket.on("join", function (user) {  
 socket.name = user  
 addLine(user + '加入了羣聊')  
 })  
 //接收到服務器發來的message事件  
 socket.on("message", function(msg) {  
 addLine(msg)  
 })  
 socket.on('disconnect', function(msg){  
 addLine(msg + '退出了羣聊');  
 })  
 socket.on('base64 file', function(msg){  
 addLine(msg)  
 })

服務器github

1.監聽客戶端發來的鏈接事件

 io.on('connection', function(socket){}

2.  監聽客戶端發來事件,並將該事件發送給全部客戶端
    

//鏈接客戶端  
io.on('connection', function(socket){  
 console.log('a user connected')  
//socket捕獲join事件  
 socket.on("join", function (name) {  
 socket.name = name;  
 usocket\[name\] = socket  
 //服務器將join事件發送給全部客戶端  
 io.emit("join", name)  
 })  
​  
 socket.on("message", function (msg) {  
 io.emit("message", msg) //將新消息廣播出去  
 })  
 socket.on('disconnect', function(msg){  
 io.emit('disconnect', socket.name);  
 })  
 socket.on('base64 file', function (msg) {  
 socket.username = msg.username;  
 // socket.broadcast.emit('base64 image', //exclude sender  
 io.sockets.emit('base64 file',  //include sender  
 msg  
 );  
 });  
});

運行

  1. 運行服務器 在powershell(須要安裝nodejs)上運行, 先npm install下載全部npm包,再運行server.js文件即
node server
  1. 運行客戶端 在瀏覽器上輸入 localhost:3000

項目代碼

demoshell

相關文章
相關標籤/搜索