电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Java實戰之用springboot+netty實現簡單的一對一聊天

瀏覽:85日期: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>二、創建netty 服務端

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('開始啟動聊天服務器');bossGroup = new NioEventLoopGroup(1);workGroup = new NioEventLoopGroup();try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChatServerInitializer()); //啟動服務器 ChannelFuture channelFuture = serverBootstrap.bind(7000).sync(); log.info('開始啟動聊天服務器結束'); channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully();} } /** * 初始化服務器 */ @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,處理業務邏輯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 {//傳過來的是json字符串String text = textWebSocketFrame.text();JSONObject jsonObject = JSON.parseObject(text);//獲取到發送人的用戶idObject msg = jsonObject.get('msg');String userId = (String) jsonObject.get('userId');Channel channel = channelHandlerContext.channel();if (msg == null) { //說明是第一次登錄上來連接,還沒有開始進行聊天,將uid加到map里面 register(userId, channel);} else { //有消息了,開始聊天了 sendMsg(msg, userId);} } /** * 第一次登錄進來 * * @param userId * @param channel */ private void register(String userId, Channel channel) {if (!ChatConfig.concurrentHashMap.containsKey(userId)) { //沒有指定的userId ChatConfig.concurrentHashMap.put(userId, channel); // 將用戶ID作為自定義屬性加入到channel中,方便隨時channel中獲取用戶ID AttributeKey<String> key = AttributeKey.valueOf('userId'); channel.attr(key).setIfAbsent(userId);} } /** * 開發發送消息,進行聊天 * * @param msg * @param userId */ private void sendMsg(Object msg, String userId) {Channel channel1 = ChatConfig.concurrentHashMap.get(userId);if (channel1 != null) { channel1.writeAndFlush(new TextWebSocketFrame('服務器時間' + LocalDateTime.now() + ' ' + msg));} } /** * 一旦客戶端連接上來,該方法被執行 * * @param ctx * @throws Exception */ @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception {log.info('handlerAdded 被調用' + ctx.channel().id().asLongText()); } /** * 斷開連接,需要移除用戶 * * @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); } /** * 處理移除,關閉通道 * * @param ctx * @param cause * @throws Exception */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close(); }}三、存儲用戶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;//判斷當前瀏覽器是否支持websocketif (window.WebSocket) { //go on socket = new WebSocket('ws://localhost:7000/chat'); //相當于channelReado, ev 收到服務器端回送的消息 socket.onmessage = function (ev) {var rt = document.getElementById('responseText');rt.value = rt.value + 'n' + ev.data; } //相當于連接開啟(感知到連接開啟) socket.onopen = function (ev) {var rt = document.getElementById('responseText');rt.value = '連接開啟了..'var userId = document.getElementById('userId').value;var myObj = {userId: userId};var myJSON = JSON.stringify(myObj);socket.send(myJSON) } //相當于連接關閉(感知到連接關閉) socket.onclose = function (ev) {var rt = document.getElementById('responseText');rt.value = rt.value + 'n' + '連接關閉了..' }} else { alert('當前瀏覽器不支持websocket')} //發送消息到服務器function send(message) { if (!window.socket) { //先判斷socket是否創建好return; } if (socket.readyState == WebSocket.OPEN) {//通過socket 發送消息var sendId = document.getElementById('sendId').value;var myObj = {userId: sendId, msg: message};var messageJson = JSON.stringify(myObj);socket.send(messageJson) } else {alert('連接沒有開啟'); }} </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='發送' onclick='send(this.form.message.value)'> <textarea style='height: 300px; width: 300px'></textarea> <input type='button' value='清空內容' onclick='document.getElementById(’responseText’).value=’’'></form></body></html>五、controller 模擬用戶登錄以及要發送信息給誰

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); }} } }六、測試

登錄成功要發消息給bbb

登錄成功要發消息給aaa

Java實戰之用springboot+netty實現簡單的一對一聊天

Java實戰之用springboot+netty實現簡單的一對一聊天

到此這篇關于Java實戰之用springboot+netty實現簡單的一對一聊天的文章就介紹到這了,更多相關springboot+netty實現一對一聊天內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Java
相關文章:
主站蜘蛛池模板: 北京发电车出租-发电机租赁公司-柴油发电机厂家 - 北京明旺盛安机电设备有限公司 | 家庭教育吧-在线家庭教育平台,专注青少年家庭教育 | 半自动预灌装机,卡式瓶灌装机,注射器灌装机,给药器灌装机,大输液灌装机,西林瓶灌装机-长沙一星制药机械有限公司 | 江苏农村商业银行招聘网_2024江苏农商行考试指南_江苏农商行校园招聘 | ★店家乐|服装销售管理软件|服装店收银系统|内衣店鞋店进销存软件|连锁店管理软件|收银软件手机版|会员管理系统-手机版,云版,App | 阴离子_阳离子聚丙烯酰胺厂家_聚合氯化铝价格_水处理絮凝剂_巩义市江源净水材料有限公司 | 炉门刀边腹板,焦化设备配件,焦化焦炉设备_沧州瑞创机械制造有限公司 | 新疆系统集成_新疆系统集成公司_系统集成项目-新疆利成科技 | 智慧消防-消防物联网系统云平台 智能化的检漏仪_气密性测试仪_流量测试仪_流阻阻力测试仪_呼吸管快速检漏仪_连接器防水测试仪_车载镜头测试仪_奥图自动化科技 | 沈阳真空机_沈阳真空包装机_沈阳大米真空包装机-沈阳海鹞真空包装机械有限公司 | 车牌识别道闸_停车场收费系统_人脸识别考勤机_速通门闸机_充电桩厂家_中全清茂官网 | 12cr1mov无缝钢管切割-15crmog无缝钢管切割-40cr无缝钢管切割-42crmo无缝钢管切割-Q345B无缝钢管切割-45#无缝钢管切割 - 聊城宽达钢管有限公司 | 视频教程导航网_视频教程之家_视频教程大全_最新视频教程分享发布平台 | 粘度计维修,在线粘度计,二手博勒飞粘度计维修|收购-天津市祥睿科技有限公司 | 北京网站建设-企业网站建设-建站公司-做网站-北京良言多米网络公司 | 中天寰创-内蒙古钢结构厂家|门式刚架|钢结构桁架|钢结构框架|包头钢结构煤棚 | 臭氧实验装置_实验室臭氧发生器-北京同林臭氧装置网 | 钢衬玻璃厂家,钢衬玻璃管道 -山东东兴扬防腐设备有限公司 | 德州网站开发定制-小程序开发制作-APP软件开发-「两山开发」 | 悬浮拼装地板_幼儿园_篮球场_悬浮拼接地板-山东悬浮拼装地板厂家 | 河南卓美创业科技有限公司-河南卓美防雷公司-防雷接地-防雷工程-重庆避雷针-避雷器-防雷检测-避雷带-避雷针-避雷塔、机房防雷、古建筑防雷等-山西防雷公司 | 南京种植牙医院【官方挂号】_南京治疗种植牙医院那个好_南京看种植牙哪里好_南京茀莱堡口腔医院 尼龙PA610树脂,尼龙PA612树脂,尼龙PA1010树脂,透明尼龙-谷骐科技【官网】 | 仿真茅草_人造茅草瓦价格_仿真茅草厂家_仿真茅草供应-深圳市科佰工贸有限公司 | 无线联网门锁|校园联网门锁|学校智能门锁|公租房智能门锁|保障房管理系统-KEENZY中科易安 | 钢绞线万能材料试验机-全自动恒应力两用机-混凝土恒应力压力试验机-北京科达京威科技发展有限公司 | 润滑脂-高温润滑脂-轴承润滑脂-食品级润滑油-索科润滑油脂厂家 | EPDM密封胶条-EPDM密封垫片-EPDM生产厂家 | 合肥风管加工厂-安徽螺旋/不锈钢风管-通风管道加工厂家-安徽风之范 | ASA膜,ASA共挤料,篷布色母料-青岛未来化学有限公司 | ★济南领跃标识制作公司★济南标识制作,标牌制作,山东标识制作,济南标牌厂 | NMRV减速机|铝合金减速机|蜗轮蜗杆减速机|NMRV减速机厂家-东莞市台机减速机有限公司 | 自动化改造_智虎机器人_灌装机_贴标机-上海圣起包装机械 | 北京晚会活动策划|北京节目录制后期剪辑|北京演播厅出租租赁-北京龙视星光文化传媒有限公司 | SEO网站优化,关键词排名优化,苏州网站推广-江苏森歌网络 | 西宁装修_西宁装修公司-西宁业之峰装饰-青海业之峰墅级装饰设计公司【官网】 | 棉柔巾代加工_洗脸巾oem_一次性毛巾_浴巾生产厂家-杭州禾壹卫品科技有限公司 | 黑龙江京科脑康医院-哈尔滨精神病医院哪家好_哈尔滨精神科医院排名_黑龙江精神心理病专科医院 | 企业彩铃制作_移动、联通、电信集团彩铃上传开通_彩铃定制_商务彩铃管理平台-集团彩铃网 | 低噪声电流前置放大器-SR570电流前置放大器-深圳市嘉士达精密仪器有限公司 | 膏剂灌装旋盖机-眼药水灌装生产线-西林瓶粉剂分装机-南通博琅机械科技 | 上海办公室设计_办公楼,写字楼装修_办公室装修公司-匠御设计 |