springboot和netty整合的聊天室--群聊

springboot和netty都是熱門的框架芥被,整合在一起,實現(xiàn)一個簡單聊天室坐榆。這個聊天室只有群聊功能拴魄。基于websocket協(xié)議實現(xiàn)的席镀。
廢話不多說匹中,看代碼
springboot的pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
    <relativePath />
    <!-- lookup parent from repository -->
</parent>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>  
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.41.Final</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>
</dependencies>

在入口類處添加代碼如下

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

netty服務(wù)端代碼

public class WebSocketServer {

private static WebSocketServer wbss;

private static final int READ_IDLE_TIME_OUT = 60; // 讀超時 s
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 是用于大數(shù)據(jù)的分區(qū)傳輸
                    // 主要用于處理大數(shù)據(jù)流顶捷,比如一個1G大小的文件如果你直接傳輸肯定會撐暴jvm內(nèi)存的;
                    // 增加之后就不用考慮這個問題了
                    pipeline.addLast(new ChunkedWriteHandler());
                    // HttpObjectAggregator 是完全的解析Http消息體請求用的
                    // 把多個消息轉(zhuǎn)換為一個單一的完全FullHttpRequest或是FullHttpResponse,
                    // 原因是HTTP解碼器會在每個HTTP消息中生成多個消息對象HttpRequest/HttpResponse,HttpContent,LastHttpContent
                    pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                    // WebSocket數(shù)據(jù)壓縮
                    pipeline.addLast(new WebSocketServerCompressionHandler());
                    // WebSocketServerProtocolHandler是配置websocket的監(jiān)聽地址/協(xié)議包長度限制
                    pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true, 10 * 1024));

                    // 當連接在60秒內(nèi)沒有接收到消息時屎篱,就會觸發(fā)一個 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應(yīng)用程序關(guān)聯(lián)的運行時對象
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            SessionGroup.inst().shutdownGracefully();
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    });
}   
}

自定義的Handler

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();
    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 協(xié)議
    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);
    }       
}   
}

SessionGroup類代碼

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);
    // 自己發(fā)送的消息不返回給自己
//      Channel channel = s.getChannel();
    // 從組中移除通道
//      group.remove(channel);
    ChannelGroupFuture future = group.writeAndFlush(new TextWebSocketFrame(json));
    future.addListener(f -> {
        System.out.println("完成發(fā)送:"+json);
//          group.add(channel);//發(fā)送消息完畢重新添加缺厉。

    });
}

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

/**
 * 關(guān)閉連接隧土, 關(guān)閉前發(fā)送一條通知消息
 */
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("關(guān)閉連接:"+echo);
            future.channel().close();
        }
    });
}

/**
 * 關(guān)閉連接
 */
public void closeSession(SocketSession session) {

    ChannelFuture sendFuture = session.getChannel().close();
    sendFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) {
            System.out.println("發(fā)送所有完成:"+session.getUser().getNickname());
        }
    });

}

/**
 * 發(fā)送消息
 * @param ctx 上下文
 * @param msg 待發(fā)送的消息
 */
public void sendMsg(ChannelHandlerContext ctx, String msg) {
    ChannelFuture sendFuture = ctx.writeAndFlush(new TextWebSocketFrame(msg));
    sendFuture.addListener(f -> {//發(fā)送監(jiān)聽
        System.out.println("對所有發(fā)送完成:"+msg);
    });
}   
}

SocketSession類如下

public class SocketSession {

public static final AttributeKey<SocketSession> SESSION_KEY = AttributeKey.valueOf("SESSION_KEY");

/**
 * 用戶實現(xiàn)服務(wù)端會話管理的核心
 */
// 通道
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) {//注意傳入?yún)?shù)channel提针。不同客戶端會有不同channel
    this.channel = channel;
    this.sessionId = buildNewSessionId();
    channel.attr(SocketSession.SESSION_KEY).set(this);
}

// 反向?qū)Ш?public static SocketSession getSession(ChannelHandlerContext ctx) {//注意ctx,不同的客戶端會有不同ctx
    Channel channel = ctx.channel();
    return channel.attr(SocketSession.SESSION_KEY).get();
}

// 反向?qū)Ш?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;
}   
}

User類

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

服務(wù)端的代碼已完成曹傀,下面進行測試关贵。寫了一個簡單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="輸入發(fā)送消息"></textarea>
    <br /><br />
    <button type="button" onclick="send()">發(fā)送</button>
    </div>      
    <script type="text/javascript">
        var webSocket;
        
        if (window.WebSocket) {
            webSocket = new WebSocket("ws://localhost:9999/ws");
        } else {
            alert("抱歉,您的瀏覽器不支持WebSocket協(xié)議!");
        }
        
        //連通之后的回調(diào)事件
        webSocket.onopen = function() {
            console.log("已經(jīng)連通了websocket");
//                setMessageInnerHTML("已經(jīng)連通了websocket");
        };
        //連接發(fā)生錯誤的回調(diào)方法
        webSocket.onerror = function(event){
            console.log("出錯了");
//              setMessageInnerHTML("連接失敗");
        };
        
        //連接關(guān)閉的回調(diào)方法
        webSocket.onclose = function(){
            console.log("連接已關(guān)閉...");

        }
        
            //接收到消息的回調(diào)方法
        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("文本太長了卖毁,少寫一點吧??");
                }
            }
        }
        
        //將消息顯示在網(wǎng)頁上
        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>

在瀏覽器隨便打開兩個網(wǎng)頁揖曾,然后都輸入http://localhost:8111/
測試效果如下圖

cheng1.jpg

cheng2.jpg

輸入相同群名落萎,就可以進入群聊。如果群名不同炭剪,會看不到在別的群留言

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
禁止轉(zhuǎn)載练链,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。
  • 序言:七十年代末奴拦,一起剝皮案震驚了整個濱河市媒鼓,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌错妖,老刑警劉巖绿鸣,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異暂氯,居然都是意外死亡潮模,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進店門痴施,熙熙樓的掌柜王于貴愁眉苦臉地迎上來擎厢,“玉大人,你說我怎么就攤上這事辣吃《猓” “怎么了?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵神得,是天一觀的道長厘惦。 經(jīng)常有香客問我,道長哩簿,這世上最難降的妖魔是什么绵估? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮卡骂,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘形入。我一直安慰自己全跨,他們只是感情好,可當我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布亿遂。 她就那樣靜靜地躺著浓若,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蛇数。 梳的紋絲不亂的頭發(fā)上挪钓,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天,我揣著相機與錄音耳舅,去河邊找鬼碌上。 笑死倚评,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的馏予。 我是一名探鬼主播天梧,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼霞丧!你這毒婦竟也來了呢岗?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤蛹尝,失蹤者是張志新(化名)和其女友劉穎后豫,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體突那,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡挫酿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了陨收。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片省容。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡搪泳,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情裆馒,我是刑警寧澤,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布回溺,位于F島的核電站啤贩,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏居触。R本人自食惡果不足惜妖混,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望轮洋。 院中可真熱鬧制市,春花似錦、人聲如沸弊予。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽汉柒。三九已至误褪,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間碾褂,已是汗流浹背兽间。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留正塌,地道東北人嘀略。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓恤溶,卻偏偏與公主長得像,于是被迫代替她去往敵國和親屎鳍。 傳聞我的和親對象是個殘疾皇子宏娄,可洞房花燭夜當晚...
    茶點故事閱讀 44,901評論 2 355