websocket的实现有很多种,像ws和socket.io,这里使用的是socket.io来实现多房间的效果。

这里的使用没有使用socket.io官方提供的namespaceroom,而是完全通过一个namespace实现的。数据传输使用JSON格式,封装了消息规范

消息体规范

const actionType = {
join:'JOIN',//加入
leave:'LEAVE',//离开
talk:'TALK',//消息
action:'ACTION',//用户操作
push:'PUSH'//系统推送
}//消息体
class MSG {
constructor(type,body){
this.type = type;
this.body= body;
}
}复制代码

安装使用

npm install socket.io-rooms --save

demo演示

把项目从github上clone下来后,执行npm start,然后打开example/index.html即可品尝到演示效果

使用方式

服务端Server

const {User,Rooms}  = require('./index')
const server = require('http').createServer();
const io = require('socket.io')(server); //大厅
io.on('connection', client => {
let user = new User();
client.emit('user',user);
client.on('join', data => {
/* 加入某个房间 */
Rooms.join(data,user,io,client)
});
client.on('message',msg=>{
if(user.roomId){
// io.to(user.roomId).emit('message',msg)
if(msg.type == 'update'){
user.update(msg.body);
}
msg.user = user.uid;
Rooms.send(user.roomId,msg)
}else{
io.emit('message',msg)
}
console.log(msg)
})
client.on('disconnect', () => {
/* … */
console.log("连接断开")
Rooms.leave(user)
});
});
server.listen();
这里传输统一使用`JSON`格式,消息`title`也以`message`为主,这里端口写的80,你可以使用其他端口,如果你是Express,也可以共用80端口。

客户端调用Client

       const socket = io('http://localhost');
log =(...args)=>{
document.getElementById('log').innerHTML +='<br/>'+args.map(item=>JSON.stringify(item)).join(' ')+'=>'+(+new Date());
} log(socket.id)
let user ={},room,client;
socket.on('connect', (c) => {
log('connect ...', socket.id);
socket.on('user',u=>{
user = u;
log('用户ID',u.uid)
});
});
socket.on('message',msg=>{
log('message:',msg)
});
function joinroom(num){
//加入房间号为1的房间
socket.emit('join',num);
}
function send(){
let msg = document.getElementById('msg').value;
socket.emit('message',{type:'TALK',body:msg})
// setInterval(function(){
// socket.emit('message',{type:'TALK',body:+new Date()})
// },2000)
}

在用户信息上,为了增加扩展性,添加了update的操作类型进行同步用户信息,这在实际中很有用。

代码很简单,就是两个类的实现, RoomsUser类,这里没有限定房间的数量,可以在初始化的时候先固定房间名和数量。源码托管于github,地址为:github.com/tianxiangbi… ,如果觉得有用,加颗小星星吧

websocket的实现有很多种,像ws和socket.io,这里使用的是socket.io来实现多房间的效果。

这里的使用没有使用socket.io官方提供的namespaceroom,而是完全通过一个namespace实现的。数据传输使用JSON格式,封装了消息规范

消息体规范

const actionType = {
join:'JOIN',//加入
leave:'LEAVE',//离开
talk:'TALK',//消息
action:'ACTION',//用户操作
push:'PUSH'//系统推送
}//消息体
class MSG {
constructor(type,body){
this.type = type;
this.body= body;
}}

安装使用

npm install socket.io-rooms --save

demo演示

把项目从github上clone下来后,执行npm start,然后打开example/index.html即可品尝到演示效果

使用方式

服务端Server

const {User,Rooms}  = require('socket.io-rooms')
const server = require('http').createServer();
const io = require('socket.io')(server);
//大厅
io.on('connection', client => {
let user = new User();
client.emit('user',user);
client.on('join', data => {
/* 加入某个房间 */
Rooms.join(data,user,io,client)
});
client.on('message',msg=>{
if(user.roomId){
// io.to(user.roomId).emit('message',msg)
if(msg.type == 'update'){
user.update(msg.body);
}
msg.user = user.uid;
Rooms.send(user.roomId,msg)
}else{
io.emit('message',msg)
}
console.log(msg)
})
client.on('disconnect', () => {
/* … */
console.log("连接断开")
Rooms.leave(user)
});
});
server.listen(80);
这里传输统一使用`JSON`格式,消息`title`也以`message`为主,这里端口写的80,你可以使用其他端口,如果你是Express,也可以共用80端口。

客户端调用Client

const socket = io('http://localhost');
log =(...args)=>{
document.getElementById('log').innerHTML +='<br/>'+args.map(item=>JSON.stringify(item)).join(' ')+'=>'+(+new Date());
}
log(socket.id)
let user ={},room,client;
socket.on('connect', (c) => {
log('connect ...', socket.id);
socket.on('user',u=>{
user = u;log('用户ID',u.uid)
});
});
socket.on('message',msg=>{
log('message:',msg)
});
function joinroom(num){
//加入房间号为1的房间
socket.emit('join',num);
}
function send(){
let msg = document.getElementById('msg').value;
socket.emit('message',{type:'TALK',body:msg}) setInterval(function(){
socket.emit('message',{type:'TALK',body:+new Date()})
},2000)
}

在用户信息上,为了增加扩展性,添加了update的操作类型进行同步用户信息,这在实际中很有用。

代码很简单,就是两个类的实现, RoomsUser类,这里没有限定房间的数量,可以在初始化的时候先固定房间名和数量。源码托管于github,地址为:https://github.com/tianxiangbing/rooms ,如果觉得有用,加颗小星星吧

使用socket.io实现多房间通信聊天室的更多相关文章

  1. 9、socket.io,websocket 前后端实时通信,(聊天室的实现)

    websocket 一种通信协议 ajax/jsonp 单工通信 websocket 全双工通信 性能高 速度快 2种方式: 1.前端的websocket 2.后端的 socket.io 一.后端so ...

  2. 使用node.js + socket.io + redis实现基本的聊天室场景

    在这篇文章Redis数据库及其基本操作中介绍了Redis及redis-cli的基本操作. 其中的publish-subscribe机制应用比较广泛, 那么接下来使用nodejs来实现该机制. 本文是对 ...

  3. 与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室

    原文:与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...

  4. 与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室

    原文:与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...

  5. vue.js+socket.io+express+mongodb打造在线聊天

    vue.js+socket.io+express+mongodb打造在线聊天 在线地址观看 http://www.chenleiming.com github地址 https://github.com ...

  6. vue.js+socket.io+express+mongodb打造在线聊天[二]

    vue.js+socket.io+express+mongodb打造在线聊天[二] 在线地址观看 http://www.chenleiming.com github地址 https://github. ...

  7. java 用socket制作一个简易多人聊天室

    代码: 服务器端Server import java.io.*; import java.net.*; import java.util.ArrayList; public class Server{ ...

  8. Android进阶(十五)socket通信——聊天室

    想做一个聊天室,花费了将近一天的时间,各种错误.讲解知识点之前,絮叨几句:动手能力还是很重要的,有时看似简单的一个问题,当你真正着手去解决的时候就有可能会遇到各种各样的问题,原因之一就是因为你的知识储 ...

  9. nodejs构建多房间简易聊天室

    1.前端界面代码 前端不是重点,够用就行,下面是前端界面,具体代码可到github下载. 2.服务器端搭建 本服务器需要提供两个功能:http服务和websocket服务,由于node的事件驱动机制, ...

随机推荐

  1. ADO.NET 三(Command)

    操作数据库需则要用到 Command 类中提供的属性和方法.下面来介绍一下如何使用 Command 类来操作数据表中的数据. Command 类概述 在 System.Data.SqlClient 命 ...

  2. Java知识回顾 (11) 异常处理

    距离最近的 Java知识回顾系列(10),2019.4.24日,到现在,已经近半年过去了. 感觉,做一件事情,如果有头无尾,实在不好,心里会一直悬着.所以,现在继续上面的内容. 再次声明,正如(1)中 ...

  3. ERROR: Cannot uninstall 'chardet'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

    pip 安装 docker库报错: ERROR: Cannot uninstall 'chardet'. It is a distutils installed project and thus we ...

  4. mybatis异常:nested exception is org.apache.ibatis.builder.BuilderException: Error resolving JdbcType

    异常详细 org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.Builde ...

  5. plsql developer中如何设置sql window显示行号

    转自:https://blog.csdn.net/qq_31302091/article/details/74931828 英文版的plsql developer中,很多时候,很多功能不去用,都不知道 ...

  6. 使nginx支持pathinfo模式

    在将fastadmin部署到虚拟机中时,遇到如下问题:当访问登录页面时,页面进行不断的循环跳转重定向.解决方法是将nginx配置为支持pathinfo的模式 以下是nginx中的配置内容: locat ...

  7. 【大数据技术能力提升_1】python基础

    .caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px so ...

  8. p6.BTC-挖矿难度

    挖矿就是不断调整nouce和header中其他可变字段,使得整个block header 的hash值小于等于target,target越小,挖矿难度越大. 出块时间设置为了10分钟,可以尽可能避免同 ...

  9. 【转】国内CPU现状

    首页 博客 学院 下载 图文课 论坛 APP CSDN                            CSDN学院                            问答 商城 VIP会员 ...

  10. Hadoop 二次排序

    需求 求每年的最高气温,年份升序,温度求最高 数据源内容如下 temperature.txt 2004 49 1981 -22 1981 -31 1965 -47 2027 -2 1964 6 203 ...