基于Springboot的聊天室Web系统设计

  • 一、新建项目与配置
  • 二、编码
  • 三、运行结果
  • 参考

一、新建项目与配置

1.新建spring项目


2.在pom.xml中添加以下内容:

 <dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId></dependency>

添加完成后IDEA会自动导入依赖

二、编码

1.新建项目结构如下:

2.WebchatApplication

package com.example.chat;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;import java.net.InetAddress;
import java.net.UnknownHostException;@SpringBootApplication
public class ChatApplication {public static void main(String[] args) throws UnknownHostException {ConfigurableApplicationContext application = SpringApplication.run(ChatApplication.class, args);Environment env = application.getEnvironment();String host = InetAddress.getLocalHost().getHostAddress();String port = env.getProperty("server.port");System.out.println("[----------------------------------------------------------]");System.out.println("聊天室启动成功!点击进入:\t http://" + host + ":" + port);System.out.println("[----------------------------------------------------------");WebSocketServer.inst().run(53134);}
}

2.SessionGroup

package com.example.chat;import com.google.gson.Gson;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.ImmediateEventExecutor;
import org.springframework.util.StringUtils;import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;public final class SessionGroup {private static SessionGroup singleInstance = new SessionGroup();// 组的映射private ConcurrentHashMap<String, ChannelGroup> groupMap = new ConcurrentHashMap<>();public static SessionGroup inst() {return singleInstance;}public void shutdownGracefully() {Iterator<ChannelGroup> groupIterator = groupMap.values().iterator();while (groupIterator.hasNext()) {ChannelGroup group = groupIterator.next();group.close();}}public void sendToOthers(Map<String, String> result, SocketSession s) {// 获取组ChannelGroup group = groupMap.get(s.getGroup());if (null == group) {return;}Gson gson=new Gson();String json = gson.toJson(result);// 自己发送的消息不返回给自己
//      Channel channel = s.getChannel();// 从组中移除通道
//      group.remove(channel);ChannelGroupFuture future = group.writeAndFlush(new TextWebSocketFrame(json));future.addListener(f -> {System.out.println("完成发送:"+json);
//          group.add(channel);//发送消息完毕重新添加。});}public void addSession(SocketSession session) {String groupName = session.getGroup();if (StringUtils.isEmpty(groupName)) {// 组为空,直接返回return;}ChannelGroup group = groupMap.get(groupName);if (null == group) {group = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);groupMap.put(groupName, group);}group.add(session.getChannel());}/*** 关闭连接, 关闭前发送一条通知消息*/public void closeSession(SocketSession session, String echo) {ChannelFuture sendFuture = session.getChannel().writeAndFlush(new TextWebSocketFrame(echo));sendFuture.addListener(new ChannelFutureListener() {public void operationComplete(ChannelFuture future) {System.out.println("关闭连接:"+echo);future.channel().close();}});}/*** 关闭连接*/public void closeSession(SocketSession session) {ChannelFuture sendFuture = session.getChannel().close();sendFuture.addListener(new ChannelFutureListener() {public void operationComplete(ChannelFuture future) {System.out.println("发送所有完成:"+session.getUser().getNickname());}});}/*** 发送消息* @param ctx 上下文* @param msg 待发送的消息*/public void sendMsg(ChannelHandlerContext ctx, String msg) {ChannelFuture sendFuture = ctx.writeAndFlush(new TextWebSocketFrame(msg));sendFuture.addListener(f -> {//发送监听System.out.println("对所有发送完成:"+msg);});}
}

4.SocketSession

package com.example.chat;import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;import java.util.HashMap;
import java.util.Map;
import java.util.UUID;public class SocketSession {public static final AttributeKey<SocketSession> SESSION_KEY = AttributeKey.valueOf("SESSION_KEY");/*** 用户实现服务端会话管理的核心*/
// 通道private Channel channel;// 用户private User user;// session唯一标示private final String sessionId;private String group;/*** session中存储的session 变量属性值*/private Map<String, Object> map = new HashMap<String, Object>();public SocketSession(Channel channel) {//注意传入参数channel。不同客户端会有不同channelthis.channel = channel;this.sessionId = buildNewSessionId();channel.attr(SocketSession.SESSION_KEY).set(this);}// 反向导航public static SocketSession getSession(ChannelHandlerContext ctx) {//注意ctx,不同的客户端会有不同ctxChannel channel = ctx.channel();return channel.attr(SocketSession.SESSION_KEY).get();}// 反向导航public static SocketSession getSession(Channel channel) {return channel.attr(SocketSession.SESSION_KEY).get();}public String getId() {return sessionId;}private static String buildNewSessionId() {String uuid = UUID.randomUUID().toString();return uuid.replaceAll("-", "");}public synchronized void set(String key, Object value) {map.put(key, value);}public synchronized <T> T get(String key) {return (T) map.get(key);}public boolean isValid() {return getUser() != null ? true : false;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String getGroup() {return group;}public void setGroup(String group) {this.group = group;}public Channel getChannel() {return channel;}
}

5.User

package com.example.chat;import java.util.Objects;public class User {public String id;public String nickname;public User(String id, String nickname) {super();this.id = id;this.nickname = nickname;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getNickname() {return nickname;}public void setNickname(String nickname) {this.nickname = nickname;}@Overridepublic boolean equals(Object o) {if (this == o)return true;if (o == null || getClass() != o.getClass())return false;User user = (User) o;return id.equals(user.getId());}@Overridepublic int hashCode() {return Objects.hash(id);}public String getUid() {return id;}
}

6.WebSocketServer

package com.example.chat;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;import java.util.concurrent.TimeUnit;public class WebSocketServer {private static WebSocketServer wbss;private static final int READ_IDLE_TIME_OUT = 60; // 读超时private static final int WRITE_IDLE_TIME_OUT = 0;// 写超时private static final int ALL_IDLE_TIME_OUT = 0; // 所有超时public static WebSocketServer inst() {return wbss = new WebSocketServer();}public void run(int port) {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer <SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();// Netty自己的http解码器和编码器,报文级别 HTTP请求的解码和编码pipeline.addLast(new HttpServerCodec());// ChunkedWriteHandler 是用于大数据的分区传输// 主要用于处理大数据流,比如一个1G大小的文件如果你直接传输肯定会撑暴jvm内存的;// 增加之后就不用考虑这个问题了pipeline.addLast(new ChunkedWriteHandler());// HttpObjectAggregator 是完全的解析Http消息体请求用的// 把多个消息转换为一个单一的完全FullHttpRequest或是FullHttpResponse,// 原因是HTTP解码器会在每个HTTP消息中生成多个消息对象HttpRequest/HttpResponse,HttpContent,LastHttpContentpipeline.addLast(new HttpObjectAggregator(64 * 1024));// WebSocket数据压缩pipeline.addLast(new WebSocketServerCompressionHandler());// WebSocketServerProtocolHandler是配置websocket的监听地址/协议包长度限制pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true, 10 * 1024));// 当连接在60秒内没有接收到消息时,就会触发一个 IdleStateEvent 事件,// 此事件被 HeartbeatHandler 的 userEventTriggered 方法处理到pipeline.addLast(new IdleStateHandler(READ_IDLE_TIME_OUT, WRITE_IDLE_TIME_OUT, ALL_IDLE_TIME_OUT, TimeUnit.SECONDS));// WebSocketServerHandler、TextWebSocketFrameHandler 是自定义逻辑处理器,pipeline.addLast(new WebSocketTextHandler());}});Channel ch = b.bind(port).syncUninterruptibly().channel();ch.closeFuture().syncUninterruptibly();// 返回与当前Java应用程序关联的运行时对象Runtime.getRuntime().addShutdownHook(new Thread() {@Overridepublic void run() {SessionGroup.inst().shutdownGracefully();bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}});}
}

7.WebSocketTextHandler

package com.example.chat;import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;import java.util.HashMap;
import java.util.Map;import static com.fasterxml.jackson.databind.type.LogicalType.Map;public class WebSocketTextHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {SocketSession session = SocketSession.getSession(ctx);TypeToken<HashMap<String, String>> typeToken = new TypeToken<HashMap<String, String>>() {};Gson gson=new Gson();java.util.Map<String,String> map = gson.fromJson(msg.text(), typeToken.getType());User user = null;switch (map.get("type")) {case "msg":Map<String, String> result = new HashMap<>();user = session.getUser();result.put("type", "msg");result.put("msg", map.get("msg"));result.put("sendUser", user.getNickname());SessionGroup.inst().sendToOthers(result, session);break;case "init":String room = map.get("room");session.setGroup(room);String nick = map.get("nick");user = new User(session.getId(), nick);session.setUser(user);SessionGroup.inst().addSession(session);break;}}@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {// 是否握手成功,升级为 Websocket 协议if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {// 握手成功,移除 HttpRequestHandler,因此将不会接收到任何消息// 并把握手成功的 Channel 加入到 ChannelGroup 中new SocketSession(ctx.channel());} else if (evt instanceof IdleStateEvent) {IdleStateEvent stateEvent = (IdleStateEvent) evt;if (stateEvent.state() == IdleState.READER_IDLE) {System.out.println("bb22");}} else {super.userEventTriggered(ctx, evt);}}}

8.新建一个html文件(可以先建一个.txt文件,写入代码后将格式改为.html)

<!DOCTYPE HTML>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>群聊天室</title>     <style type="text/css">body {margin-right:50px;margin-left:50px;}.ddois {position: fixed;left: 120px;bottom: 30px;       }</style>
</head>
<body>群名:<input type="text" id="room" name="group" placeholder="请输入群"><br /><br />昵称:<input type="text" id="nick" name="name" placeholder="请输入昵称"><br /><br /><button type="button" onclick="enter()">进入聊天群</button><br /><br />        <div id="message"></div><br /><br />        <div class="ddois"><textarea name="send" id="text" rows="10" cols="30" placeholder="输入发送消息"></textarea><br /><br /><button type="button" onclick="send()">发送</button></div>      <script type="text/javascript">var webSocket;if (window.WebSocket) {webSocket = new WebSocket("ws://localhost:53134/ws");} else {alert("抱歉,您的浏览器不支持WebSocket协议!");}//连通之后的回调事件webSocket.onopen = function() {console.log("已经连通了websocket");
//                setMessageInnerHTML("已经连通了websocket");};//连接发生错误的回调方法webSocket.onerror = function(event){console.log("出错了");
//              setMessageInnerHTML("连接失败");};//连接关闭的回调方法webSocket.onclose = function(){console.log("连接已关闭...");}//接收到消息的回调方法webSocket.onmessage = function(event){console.log("bbdds");var data = JSON.parse(event.data)var msg = data.msg;var nick = data.sendUser;switch(data.type){case 'init':console.log("mmll");break;case 'msg':console.log("bblld");setMessageInnerHTML(nick+":  "+msg);break;default:break;}}           function enter(){var map = new Map();var nick=document.getElementById('nick').value;var room=document.getElementById('room').value;map.set("type","init");map.set("nick",nick);console.log(room);map.set("room",room);var message = Map2Json(map);webSocket.send(message);                    }function send() {var msg = document.getElementById('text').value;var nick = document.getElementById('nick').value;console.log("1:"+msg);if (msg != null && msg != ""){var map = new Map();map.set("type","msg");map.set("msg",msg);var map2json=Map2Json(map);if (map2json.length < 8000){console.log("4:"+map2json);webSocket.send(map2json);}else {console.log("文本太长了,少写一点吧												

基于Springboot的聊天室Web系统设计相关推荐

  1. SpringBoot + Vue 实现基于 WebSocket 的聊天室(单聊)

    前言 在前一篇文章SpringBoot 集成 STOMP 实现一对一聊天的两种方法中简单介绍了如何利用 STOMP 实现单聊,本文则将以一个比较完整的示例展示实际应用,不过本文并未使用 STOMP,而 ...

  2. java websocket netty_用SpringBoot集成Netty开发一个基于WebSocket的聊天室

    前言 基于SpringBoot,借助Netty控制长链接,使用WebSocket协议做一个实时的聊天室. 项目效果 项目统一登录路径:http://localhost:8080/chat/netty ...

  3. 基于java的聊天室系统设计与实现(项目报告+开题报告+答辩PPT+源代码+部署视频)

    项目报告 Java网络聊天室系统的设计与实现 计算机从出现到现在有了飞速的发展,现阶段的计算机已经不单单是用于进行运算的独立的个体了,跟随计算机一同发展的还有互联网技术,经过了长久的发展,互联网技术有 ...

  4. 基于WebSocket实现聊天室(Node)

    基于WebSocket实现聊天室(Node) WebSocket是基于TCP的长连接通信协议,服务端可以主动向前端传递数据,相比比AJAX轮询服务器,WebSocket采用监听的方式,减轻了服务器压力 ...

  5. java开发websocket聊天室_java实现基于websocket的聊天室

    [实例简介] java实现基于websocket的聊天室 [实例截图] [核心代码] chatMavenWebapp └── chat Maven Webapp ├── pom.xml ├── src ...

  6. 基于linux网络聊天室的设计,参考基于linux网络聊天室的设计.doc

    参考基于linux网络聊天室的设计 长沙理工大学<高级操作系统>课程设计报告学 院 计算机与通信工程 专 业 计算机科学与技术 班 级 学 号 学生姓名 指导教师 课程成绩 完成日期 课程 ...

  7. SSM(五)基于webSocket的聊天室

    SSM(五)基于webSocket的聊天室 前言 不知大家在平时的需求中有没有遇到需要实时处理信息的情况,如站内信,订阅,聊天之类的.在这之前我们通常想到的方法一般都是采用轮训的方式每隔一定的时间向服 ...

  8. Android 基于Socket的聊天室

    原文地址为: Android 基于Socket的聊天室 Socket是TCP/IP协议上的一种通信,在通信的两端各建立一个Socket,从而在通信的两端之间形成网络虚拟链路.一旦建立了虚拟的网络链路, ...

  9. 从0实现基于Linux socket聊天室-实现聊天室的公聊、私聊功能-4

    前面文章链接如下: <从0实现基于Linux socket聊天室-多线程服务器模型-1> <从0实现基于Linux socket聊天室-多线程服务器一个很隐晦的错误-2> &l ...

最新文章

  1. Nagios的安装和基本配置(一:知识点总结及环境准备)
  2. 说说CSRF的***
  3. sql服务器登录名为电脑名如何修改,如何恢复数据库的账号 登录名/用户名等
  4. 深度学习笔记 第四门课 卷积神经网络 第三周 目标检测
  5. 使用JCrop进行图片裁剪,裁剪js说明,裁剪预览,裁剪上传,裁剪设计的图片处理的工具类和代码
  6. .NET LINQ分析AWS ELB日志避免996
  7. Fortinet:行走在网络和安全融合领域的最前列
  8. 使用c++查看linux服务器某个进程正在使用的内存_精选20个常用的Linux命令
  9. TreeView控件 1202
  10. C#中调用SSIS包的问题
  11. MySQL中的空间扩展
  12. 我眼中BA(业务需求分析师)的技能广度和深度
  13. 关于软件测试里面的Fault Error Failure 差别
  14. 控制台上对同一个设备进行数据收发监控
  15. 封装el-select(全球国家名字及国家区号),select 输入框回显
  16. 【沧海拾昧】微机原理:8086/8088中断系统
  17. Pytorch警告UserWarning: Loky-backed parallel loops cannot be called in a multiprocessing
  18. 实测:华为鸿蒙系统比 Android 系统快 60%!
  19. 安徽阜阳育英计算机学校,阜阳育英中学
  20. MTK平台安卓Q 10.0 camera驱动移植——sensor

热门文章

  1. mysql外键约束案例_SQLServer FOREIGN KEY外键约束讲解及使用实例
  2. PS学习笔记----图层蒙版
  3. mysql查询表内所有字段名和备注
  4. MATLAB初级绘图学习笔记
  5. selenium修改readonly属性的方法
  6. Construct2 水波特效
  7. 服务端渲染or客户端渲染
  8. 【OpenCV-Python】21.OpenCV的二维直方图
  9. G1调优实践日记--被误解的MetaspaceSize
  10. graphics.drawString中文乱码