久久福利_99r_国产日韩在线视频_直接看av的网站_中文欧美日韩_久久一

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Java實(shí)戰(zhàn)之用springboot+netty實(shí)現(xiàn)簡(jiǎn)單的一對(duì)一聊天

瀏覽:80日期:2022-08-13 16:05:31
一、引入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.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'> <modelVersion>4.0.0</modelVersion> <groupId>com.chat.info</groupId> <artifactId>chat-server</artifactId> <version>1.0-SNAPSHOT</version> <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.4.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><!-- web --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.33.Final</version></dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId></dependency><!-- fastjson --><dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.56</version></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency> </dependencies> <build><plugins> <plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId> </plugin></plugins> </build></project>二、創(chuàng)建netty 服務(wù)端

package com.chat.server; import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioServerSocketChannel;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component; import javax.annotation.PostConstruct;import javax.annotation.PreDestroy; @Component@Slf4jpublic class ChatServer { private EventLoopGroup bossGroup; private EventLoopGroup workGroup; private void run() throws Exception {log.info('開(kāi)始啟動(dòng)聊天服務(wù)器');bossGroup = new NioEventLoopGroup(1);workGroup = new NioEventLoopGroup();try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChatServerInitializer()); //啟動(dòng)服務(wù)器 ChannelFuture channelFuture = serverBootstrap.bind(7000).sync(); log.info('開(kāi)始啟動(dòng)聊天服務(wù)器結(jié)束'); channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully();} } /** * 初始化服務(wù)器 */ @PostConstruct() public void init() {new Thread(() -> { try {run(); } catch (Exception e) {e.printStackTrace(); }}).start(); } @PreDestroy public void destroy() throws InterruptedException {if (bossGroup != null) { bossGroup.shutdownGracefully().sync();}if (workGroup != null) { workGroup.shutdownGracefully().sync();} }}

package com.chat.server; import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;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.stream.ChunkedWriteHandler; public class ChatServerInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline();//使用http的編碼器和解碼器pipeline.addLast(new HttpServerCodec());//添加塊處理器pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpObjectAggregator(8192)); pipeline.addLast(new WebSocketServerProtocolHandler('/chat'));//自定義handler,處理業(yè)務(wù)邏輯pipeline.addLast(new ChatServerHandler()); }}

package com.chat.server; import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.chat.config.ChatConfig;import io.netty.channel.Channel;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;import io.netty.util.AttributeKey;import lombok.extern.slf4j.Slf4j; import java.time.LocalDateTime; @Slf4jpublic class ChatServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {//傳過(guò)來(lái)的是json字符串String text = textWebSocketFrame.text();JSONObject jsonObject = JSON.parseObject(text);//獲取到發(fā)送人的用戶idObject msg = jsonObject.get('msg');String userId = (String) jsonObject.get('userId');Channel channel = channelHandlerContext.channel();if (msg == null) { //說(shuō)明是第一次登錄上來(lái)連接,還沒(méi)有開(kāi)始進(jìn)行聊天,將uid加到map里面 register(userId, channel);} else { //有消息了,開(kāi)始聊天了 sendMsg(msg, userId);} } /** * 第一次登錄進(jìn)來(lái) * * @param userId * @param channel */ private void register(String userId, Channel channel) {if (!ChatConfig.concurrentHashMap.containsKey(userId)) { //沒(méi)有指定的userId ChatConfig.concurrentHashMap.put(userId, channel); // 將用戶ID作為自定義屬性加入到channel中,方便隨時(shí)channel中獲取用戶ID AttributeKey<String> key = AttributeKey.valueOf('userId'); channel.attr(key).setIfAbsent(userId);} } /** * 開(kāi)發(fā)發(fā)送消息,進(jìn)行聊天 * * @param msg * @param userId */ private void sendMsg(Object msg, String userId) {Channel channel1 = ChatConfig.concurrentHashMap.get(userId);if (channel1 != null) { channel1.writeAndFlush(new TextWebSocketFrame('服務(wù)器時(shí)間' + LocalDateTime.now() + ' ' + msg));} } /** * 一旦客戶端連接上來(lái),該方法被執(zhí)行 * * @param ctx * @throws Exception */ @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception {log.info('handlerAdded 被調(diào)用' + ctx.channel().id().asLongText()); } /** * 斷開(kāi)連接,需要移除用戶 * * @param ctx * @throws Exception */ @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {removeUserId(ctx); } /** * 移除用戶 * * @param ctx */ private void removeUserId(ChannelHandlerContext ctx) {Channel channel = ctx.channel();AttributeKey<String> key = AttributeKey.valueOf('userId');String userId = channel.attr(key).get();ChatConfig.concurrentHashMap.remove(userId);log.info('用戶下線,userId:{}', userId); } /** * 處理移除,關(guān)閉通道 * * @param ctx * @param cause * @throws Exception */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close(); }}三、存儲(chǔ)用戶channel 的map

package com.chat.config; import io.netty.channel.Channel; import java.util.concurrent.ConcurrentHashMap; public class ChatConfig { public static ConcurrentHashMap<String, Channel> concurrentHashMap = new ConcurrentHashMap(); }四、客戶端html

<!DOCTYPE html><html lang='en' xmlns:th='http://www.thymeleaf.org'><head> <meta charset='UTF-8'> <title>Title</title> <script>var socket;//判斷當(dāng)前瀏覽器是否支持websocketif (window.WebSocket) { //go on socket = new WebSocket('ws://localhost:7000/chat'); //相當(dāng)于channelReado, ev 收到服務(wù)器端回送的消息 socket.onmessage = function (ev) {var rt = document.getElementById('responseText');rt.value = rt.value + 'n' + ev.data; } //相當(dāng)于連接開(kāi)啟(感知到連接開(kāi)啟) socket.onopen = function (ev) {var rt = document.getElementById('responseText');rt.value = '連接開(kāi)啟了..'var userId = document.getElementById('userId').value;var myObj = {userId: userId};var myJSON = JSON.stringify(myObj);socket.send(myJSON) } //相當(dāng)于連接關(guān)閉(感知到連接關(guān)閉) socket.onclose = function (ev) {var rt = document.getElementById('responseText');rt.value = rt.value + 'n' + '連接關(guān)閉了..' }} else { alert('當(dāng)前瀏覽器不支持websocket')} //發(fā)送消息到服務(wù)器function send(message) { if (!window.socket) { //先判斷socket是否創(chuàng)建好return; } if (socket.readyState == WebSocket.OPEN) {//通過(guò)socket 發(fā)送消息var sendId = document.getElementById('sendId').value;var myObj = {userId: sendId, msg: message};var messageJson = JSON.stringify(myObj);socket.send(messageJson) } else {alert('連接沒(méi)有開(kāi)啟'); }} </script></head><body><h1 th:text='${userId}'></h1><input type='hidden' th:value='${userId}' id='userId'><input type='hidden' th:value='${sendId}' id='sendId'><form onsubmit='return false'> <textarea name='message' style='height: 300px; width: 300px'></textarea> <input type='button' value='發(fā)送' onclick='send(this.form.message.value)'> <textarea style='height: 300px; width: 300px'></textarea> <input type='button' value='清空內(nèi)容' onclick='document.getElementById(’responseText’).value=’’'></form></body></html>五、controller 模擬用戶登錄以及要發(fā)送信息給誰(shuí)

package com.chat.controller; import com.chat.config.ChatConfig;import io.netty.channel.Channel;import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestParam;@Controllerpublic class ChatController { @GetMapping('login') public String login(Model model, @RequestParam('userId') String userId, @RequestParam('sendId') String sendId) {model.addAttribute('userId', userId);model.addAttribute('sendId', sendId);return 'chat'; } @GetMapping('sendMsg') public String login(@RequestParam('sendId') String sendId) throws InterruptedException {while (true) { Channel channel = ChatConfig.concurrentHashMap.get(sendId); if (channel != null) {channel.writeAndFlush(new TextWebSocketFrame('test'));Thread.sleep(1000); }} } }六、測(cè)試

登錄成功要發(fā)消息給bbb

登錄成功要發(fā)消息給aaa

Java實(shí)戰(zhàn)之用springboot+netty實(shí)現(xiàn)簡(jiǎn)單的一對(duì)一聊天

Java實(shí)戰(zhàn)之用springboot+netty實(shí)現(xiàn)簡(jiǎn)單的一對(duì)一聊天

到此這篇關(guān)于Java實(shí)戰(zhàn)之用springboot+netty實(shí)現(xiàn)簡(jiǎn)單的一對(duì)一聊天的文章就介紹到這了,更多相關(guān)springboot+netty實(shí)現(xiàn)一對(duì)一聊天內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 91中文视频 | 久草热8精品视频在线观看 欧美全黄 | 男人亚洲天堂网 | 亚洲高清av | 久久亚洲一区 | 国产一区二区三区不卡在线观看 | 国产精品久久久久久久久久久久久 | 欧美激情一区二区三区 | 久久窝| 精品在线一区 | 中文字幕亚洲精品 | 久久精品国产一区 | 久久久久一区 | 日日操操 | 欧美在线一区二区 | 成人av网址在线观看 | 日韩精品一区二区三区视频播放 | 欧美性猛交xxxx黑人猛交 | 日韩欧美一区二区三区免费观看 | 四虎永久免费 | 91精品国产综合久久久亚洲 | 91精品国产色综合久久 | 亚洲精品三级 | 黄色毛片在线看 | 国产成人一区二区三区 | 国产精品伦理一区 | 国产成人在线电影 | 爱爱爱av | 欧美日韩高清在线一区 | 天堂av2020| av免费网站在线观看 | 日本99精品| 日韩免费视频 | 特黄毛片 | 亚洲在线一区二区 | 99国产精品久久久久久久 | 久久久久久久9 | 久久久精| 国产日韩中文字幕 | www中文字幕在线观看 | 久久精品一 |