iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java实战之用springboot+netty实现简单的一对一聊天
  • 503
分享到

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

2024-04-02 19:04:59 503人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录一、引入pom二、创建Netty 服务端三、存储用户channel 的map四、客户端html五、controller 模拟用户登录以及要发送信息给

一、引入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
@Slf4j
public 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;
 
@Slf4j
public 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);
        //获取到发送人的用户id
        Object 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);
        }
 
    }
 
    
    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);
        }
    }
 
    
    private void sendMsg(Object msg, String userId) {
        Channel channel1 = ChatConfig.concurrentHashMap.get(userId);
        if (channel1 != null) {
            channel1.writeAndFlush(new TextWebSocketFrame("服务器时间" + LocalDateTime.now() + " " + msg));
        }
    }
 
 
    
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerAdded 被调用" + ctx.channel().id().asLongText());
    }
 
    
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        removeUserId(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);
    }
 
    
    @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;
        //判断当前浏览器是否支持websocket
        if (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 id="responseText" 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;
@Controller
public 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实现简单的一对一聊天的文章就介绍到这了,更多相关springboot+netty实现一对一聊天内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Java实战之用springboot+netty实现简单的一对一聊天

本文链接: https://www.lsjlt.com/news/124525.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Java实战之用springboot+netty实现简单的一对一聊天
    目录一、引入pom二、创建netty 服务端三、存储用户channel 的map四、客户端html五、controller 模拟用户登录以及要发送信息给...
    99+
    2024-04-02
  • 怎么用SpringBoot+Netty实现简单聊天室
    本篇内容主要讲解“怎么用SpringBoot+Netty实现简单聊天室”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用SpringBoot+Netty实现简单聊天室”吧!一、实现1.User...
    99+
    2023-06-29
  • SpringBoot+Netty实现简单聊天室的示例代码
    目录一、实现1.User类2.SocketSession类3.SessionGroup4.WebSocketTextHandler类5.WebSocketServer类6.index...
    99+
    2024-04-02
  • Java实战之基于TCP实现简单聊天程序
    目录一、如何实现TCP通信二、编写C/S架构聊天程序1.编写服务器端程序 - Server.java2.编写客户端程序 - Client.java3.测试服务器端与客户端能否通信4....
    99+
    2024-04-02
  • Java聊天室之实现客户端一对一聊天功能
    目录一、题目描述二、解题思路三、代码详解多学一个知识点一、题目描述 题目实现:不同的客户端之间需要进行通信,一个客户端与指定的另一客户端进行通信,实现一对一聊天功能。 实现一个客户端...
    99+
    2022-11-13
    Java实现聊天室 Java 聊天室 Java  客户端一对一聊天
  • Go语言实现一个简单的并发聊天室的项目实战
    目录写在前面并发聊天服务器具体代码服务端客户端 总结写在前面 Go语言在很多方面天然的具备很多便捷性,譬如网络编程,并发编程。而通道则又是Go语言实现并发编程的重要工具,因...
    99+
    2024-04-02
  • 怎么用java实现一个简易的聊天室
    要实现一个简易的聊天室,可以使用Java的Socket编程实现。下面是一个简单的实现示例: 服务器端代码: import java....
    99+
    2024-02-29
    java
  • golang实现一个简单的websocket聊天室功能
    基本原理: 1.引入了 golang.org/x/net/websocket 包。 2.监听端口。 3.客户端连接时,发送结构体: {"type":"login","uid":"我是...
    99+
    2024-04-02
  • Java实现一个简易聊天室流程
    目录文件传输Tcp方式Udp 方式简易聊天室的实现接收端发送端启动说到网络,相信大家都对TCP、UDP和HTTP协议这些都不是很陌生,学习这部分应该先对端口、Ip地址这些基础知识有一...
    99+
    2022-11-13
    Java聊天室 Java简易聊天室
  • 如何使用Springboot+netty实现Web聊天室
    这篇文章主要为大家展示了“如何使用Springboot+netty实现Web聊天室”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何使用Springboot+netty实现Web聊天室”这篇文章...
    99+
    2023-06-21
  • Java实现简单的聊天室功能
    本文实例为大家分享了Java实现简单聊天室功能的具体代码,供大家参考,具体内容如下 一、客户端的创建 1.我们可以用Socket来创建客户端 public class Client...
    99+
    2024-04-02
  • Java实现简单聊天机器人
    本文实例为大家分享了Java实现简单聊天机器人的具体代码,供大家参考,具体内容如下 整个小案例:整合了Java socket编程、jdbc知识(ORM/DAO) 创建数据库和表,准备...
    99+
    2024-04-02
  • java NIO实现简单聊天程序
    本文实例为大家分享了java NIO实现简单聊天程序的具体代码,供大家参考,具体内容如下 服务端 功能: 1、接受客户端连接 2、发送消息 3、读取客户端消息 Server.jav...
    99+
    2024-04-02
  • Java实现简单QQ聊天工具
    Java实现简单的类似QQ聊天工具,供大家参考,具体内容如下 所使用到的知识点: java socket编程之TCP协议java Swing简单的java多线程 运行截图: 服务...
    99+
    2024-04-02
  • Springboot+WebSocket实现一对一聊天和公告的示例代码
    1.POM文件导入Springboot整合websocket的依赖 <dependency> <groupId>...
    99+
    2024-04-02
  • 如何使用MySQL和Java实现一个简单的聊天室功能
    要使用MySQL和Java实现一个简单的聊天室功能,你需要进行以下步骤:1. 创建数据库和表:使用MySQL创建一个数据库,并在该数...
    99+
    2023-10-10
    MySQL
  • TP6中使用gateway-worker 实现一对一聊天。
    TP6 中使用 gateway-worker 安装: composer require topthink/think-worker 更新镜像 composer config -g repo.packagist composer https:...
    99+
    2023-09-12
    gateway php 服务器 在线聊天
  • 如何利用C++实现一个简单的聊天室程序?
    如何利用C++实现一个简单的聊天室程序?在信息时代,人们越来越注重网络交流。而聊天室作为一种常见的沟通工具,具有实时性和交互性的特点,被广泛应用于各个领域。本文将介绍如何利用C++语言实现一个简单的聊天室程序。首先,我们需要建立一个基于客户...
    99+
    2023-11-04
    C++ 实现 聊天室程序
  • Java实现简单局域网聊天室
    本文实例为大家分享了Java实现简单局域网聊天室的具体代码,供大家参考,具体内容如下 Java 的Socket编程: 1、TCP协议是面向连接的、可靠的、有序的、以字节流的方式发送数...
    99+
    2024-04-02
  • 基于websocket实现简单聊天室对话
    本文实例为大家分享了websocket实现简单聊天室对话的具体代码,供大家参考,具体内容如下 首先搭建一个node的环境,在app.js中写入以下代码 npm install s...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作