1、功能介绍
和之前的NIO实现群聊机制一样,这里使用Netty实现:
- 1、当有新用户上线时,通知其他用户上线,下线同理
- 2、用户x发送一条消息,服务器端转发给其他所有在线服务器
2、代码结构

3、GroupChatServer
package groupchat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import java.beans.Encoder;
public class GroupChatServer {
//监听端口
private int port;
public GroupChatServer(int port){
this.port = port;
}
//编写run方法,处理客户端的请求
public void run() throws Exception{
//创建两个线程组
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
//其中NioEventLoppGroup默认八个线程
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//创建ServerBootstrap,服务器启动引导类
ServerBootstrap b = new ServerBootstrap();
//设置ServerBootstrap相关参数
b.group(bossGroup, workerGroup)//roup函数设置两个EventLoop
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
//指定相关handler
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//获取pipeline
ChannelPipeline pipeline = ch.pipeline();
//向pipeline中加入解码器
pipeline.addLast("decoder", new StringDecoder());
//向pipeline中加入编码器
pipeline.addLast("encoder", new StringDecoder(

本文介绍了如何利用Netty构建一个群聊系统,详细讲解了功能介绍、代码结构、服务器端(GroupChatServer和GroupChatServerHandler)、客户端(GroupChatClient和GroupChatClientHandler)的实现,并提供了测试步骤。在实施过程中,遇到并解决了IP或端口设置错误导致的Exception异常问题。
最低0.47元/天 解锁文章
858

被折叠的 条评论
为什么被折叠?



