Springboot+netty实现Web聊天室

目录
  • 一、项目的创建
  • 二、代码编写
  • 三、运行效果

一、项目的创建

新建Spring项目:

选择JDK版本:

选择Spring Web:

项目名称和位置的设置:

二、代码编写

导入.jar包:

gson: https://search.maven.org/artifact/com.google.code.gson/gson/2.8.9/jar

DemoApplication:

package com.example.demo;

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 DemoApplication {

    public static void main(String[] args) throws UnknownHostException {
        ConfigurableApplicationContext application = SpringApplication.run(DemoApplication.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);
    }

}

User:

package com.example.demo;

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;
    }

    @Override
    public 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());
    }

    @Override
    public int hashCode() {

        return Objects.hash(id);
    }

    public String getUid() {

        return id;
    }
}

SessionGroup:

package com.example.demo;

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);
        });
    }
}

SocketSession:

package com.example.demo;

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。不同客户端会有不同channel
        this.channel = channel;
        this.sessionId = buildNewSessionId();
        channel.attr(SocketSession.SESSION_KEY).set(this);
    }

    // 反向导航
    public static SocketSession getSession(ChannelHandlerContext ctx) {//注意ctx,不同的客户端会有不同ctx
        Channel 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;
    }
}

WebSocketServer:

package com.example.demo;

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>() {
                    @Override
                    protected 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,LastHttpContent
                        pipeline.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() {
            @Override
            public void run() {
                SessionGroup.inst().shutdownGracefully();
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });
    }
}

WebSocketTextHandler:

package com.example.demo;

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;

public class WebSocketTextHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //@Override
    protected void channelRead(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);
        }
    }

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }
}

之后项目外创建一个test.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("文本太长了,少写一点吧");
                }
            }
        }

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById("message").innerHTML += innerHTML + "<br/>";
        }

        function Map2Json(map) {
            var str = "{";
            map.forEach(function (value, key) {
                str += '"'+key+'"'+':'+ '"'+value+'",';
            })
            str = str.substring(0,str.length-1)
            str +="}";
            return str;
        }        

    </script>

</body>
</html>

先运行项目,然后运行html

三、运行效果

到此这篇关于Springboot+netty实现Web聊天室的文章就介绍到这了,更多相关Springboot netty 聊天室内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringBoot+WebSocket搭建简单的多人聊天系统

    前言 今天闲来无事,就来了解一下WebSocket协议.来简单了解一下吧. WebSocket是什么 首先了解一下WebSocket是什么?WebSocket是一种在单个TCP连接上进行全双工通信的协议.这是一种比较官方的说法,简单点来说就是,在一次TCP连接中,通信的双方可以相互通信.比如A和B在打电话,A说话的时候,B也可以说话来进行信息的交互,这就叫做全双工通信.对应的是单工通信,和半双工通信,单工通信就是只能由A向B通信,比如电脑和打印机.半双工通信是可以AB可以互相通信,但是同一时间只

  • SpringBoot+Websocket实现一个简单的网页聊天功能代码

    最近做了一个SpringBoot的项目,被SpringBoot那简介的配置所迷住.刚好项目中,用到了websocket.于是,我就想着,做一个SpringBoot+websocket简单的网页聊天Demo. 效果展示: 当然,项目很简单,没什么代码,一眼就能明白 导入websocket的包. 通过使用SpringBoot导入包的时候,我们可以发现,很多包都是以 spring-boot-starter 开头的,对于我这种强迫症 ,简直是福音 <dependency> <groupId>

  • Java实战之用springboot+netty实现简单的一对一聊天

    一.引入pom <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4

  • Springboot+WebSocket实现一对一聊天和公告的示例代码

    1.POM文件导入Springboot整合websocket的依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.1.6.RELEASE</version> </dependency> 2.注册WebSocket的

  • SpringBoot中webSocket实现即时聊天

    即时聊天 这个使用了websocket,在springboot下使用很简单.前端是小程序,这个就比较坑,小程序即时聊天上线需要域名并且使用wss协议,就是ws+ssl更加安全.但是要上线这还不够,你必须为企业主体开发者.个人开发者即时聊天属于社交.不在服务类目内,审核会不通过!!! 功能 :我们的小程序是个二手交易小程序,即时聊天对于一个后台服务器只是单核2g的来说有点抗不住.所以在双方都在线的时候没有存储聊天消息,只是在单方不在线时存储了离线消息.而且只能发三条离线消息.仿照了csdn的聊天.

  • Springboot+netty实现Web聊天室

    目录 一.项目的创建 二.代码编写 三.运行效果 一.项目的创建 新建Spring项目: 选择JDK版本: 选择Spring Web: 项目名称和位置的设置: 二.代码编写 导入.jar包: gson: https://search.maven.org/artifact/com.google.code.gson/gson/2.8.9/jar DemoApplication: package com.example.demo; import org.springframework.boot.Spr

  • SpringBoot+Netty实现简单聊天室的示例代码

    目录 一.实现 1.User类 2.SocketSession类 3.SessionGroup 4.WebSocketTextHandler类 5.WebSocketServer类 6.index.html 二.效果 一.实现 1.User类 import java.util.Objects; public class User {     public String id;     public String nickname;     public User(String id, Strin

  • 使用socket.io制做简易WEB聊天室

    使用socket.io做一个简单的WEB聊天室,可消息私发,供大家参考,具体内容如下 1. 创建一个空的工程目录 空的目录命名为chat-web 2. 创建package.json 使用命令:npm init,会引导你设置package.json的内容. 3.安装依赖包 使用命令: npm install --save express npm install --save socket.io 安装完成后你会在工程目录看见有自动生成的node_modules文件夹 4.编写index.js脚本 v

  • WebSocket实现Web聊天室功能

    本文为大家分享了WebSocket实现Web聊天室的具体代码,供大家参考,具体内容如下 一.客户端 JS代码如下: /* * 这部分js将websocket封装起来 */ var websocket = null; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8080/GoodMan/ChatService"); } else { alert(

  • .net core使用FastHttpApi构建web聊天室实例代码

    前言 一般在dotnet core下构建使用web服务应用都使用asp.net core,但通过FastHttpApi组建也可以方便地构建web服务应用,在FastHttpApi功能的支持下构建多人聊天室是件非常简单的事情,通过组件并不需要了解WebSocket知识即可简单构建,以下讲解一下通过FastHttpApi如何构建一个简单的多人聊室. 创建项目 使用FastHttpApi构建一个WEB服务只需要创建一个普通ConsoleApp( 控制台应用) 创建项目后需要在Nuget中添加引用Fas

  • JAVA Netty实现聊天室+私聊功能的示例代码

    功能介绍 使用Netty框架实现聊天室功能,服务器可监控客户端上下限状态,消息转发.同时实现了点对点私聊功能.技术点我都在代码中做了备注,这里不再重复写了.希望能给想学习netty的同学一点参考. 服务器代码 服务器入口代码 package nio.test.netty.groupChat; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.chann

  • vue+web端仿微信网页版聊天室功能

    一.项目介绍 基于Vue2.5.6+Vuex+vue-cli+vue-router+vue-gemini-scrollbar+swiper+elementUI等技术混合架构开发的仿微信web端聊天室--vueWebChat,实现了发送消息.表情(动图),图片.视频预览,右键菜单.截屏.截图可直接粘贴至文本框进行发送. 二.技术框架 •MVVM框架:Vue2.5.6 •状态管理:Vuex •页面路由:Vue-router •iconfont图标:阿里巴巴字体图标库 •自定义滚动条:vue-gemi

  • java基于netty NIO的简单聊天室的实现

    一.为何要使用netty开发 由于之前已经用Java中的socket写过一版简单的聊天室,这里就不再对聊天室的具体架构进行细致的介绍了,主要关注于使用netty框架重构后带来的改变.对聊天室不了解的同学可以先看下我的博客(<JAVA简单聊天室的实现>) 本篇博客所使用的netty版本为4.1.36,完整工程已上传到Github(https://github.com/Alexlingl/Chatroom),其中lib文件夹下有相应的netty jar包和source包,自行导入即可. 1.为何要

  • java web实现简单聊天室

    目标 servlet.jsp实现简单聊天室,用户通过浏览器登录后进入聊天室,可发送消息进行群聊,点击聊天信息框中的用户名可实现拍一拍功能. 基础知识 数据的存取 setAttribute / getAttribute request请求对象 :有效时间短 ServletContext上下文对象:一直存在于服务器,存储公有. 共享数据 Session会话对象:独立 网站默认页面一般是index.jsp 实现思路 1.登录页面 login.jsp 输入昵称 2.编写一个LoginSevlet,处理登

随机推荐