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. PHP网文

    1.php底层运行机制及原理 https://cloud.tencent.com/developer/article/1055801

  2. SQL 向表中添加字段

    如果要在数据表中添加一个字段,应该如何表示呢?下面就为您介绍表添加字段的SQL语句的写法,希望可以让您对SQL语句有更深的认识. 通用式: alter table [表名] add [字段名] 字段属 ...

  3. IdentityServer4(客户端授权模式)

    1.新建三个项目 IdentityServer:端口5000 IdentityAPI:端口5001 IdentityClient: 2.在IdentityServer项目中添加IdentityServ ...

  4. java之struts2之异常处理

    1.在应用项目中,异常的出现时很正常的.而且项目上线后发生异常也很正常的.那么需要对这些异常有相应的处理机制,以便客户能够看你到更加友好的界面.Struts2中提供了异常处理机制. 2.Struts中 ...

  5. debug 查询服务日志,用于定位服务在运行和启动过程中出现的问题

    vim /usr/lib/systemd/system/sshd.service [Unit] Description=OpenSSH server daemon Documentation=man: ...

  6. Ubuntu 下安装 OpenSSH Server

    Ubuntu 下安装 OpenSSH Server 是无比轻松的一件事情,需要的命令只有一条: sudo apt-get install openssh-server (查看返回的结果,如果没有出错, ...

  7. 【转载】 C#中通过Where方法查找出所有符合条件的元素集合

    在C#的List集合对象中,FirstOrDefault方法可以用于查找List集合中符合条件的第一个元素,如果需要根据条件查找到List集合中的所有符合条件的元素对象集合,则需要使用到List集合的 ...

  8. 阿里云ssl协议发布qq邮件

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx. ...

  9. vue页面跳转

    一.在template中的常见写法: <router-link to="/recommend"> <button class="button" ...

  10. Apache Commons FileUpload实现文件上传

    一.Apache Commons-FileUpload简介 Apache Commons是一个专注于可重用Java组件的所有方面的 Apache 项目. Apache Commons项目由三个部分组成 ...