Java+Netty 实现即时通讯示例

博客给出Java + Netty实现即时通讯的完整代码示例及注释。创建类启动服务器,在run方法处理客户端连接和网络IO操作,设置相关对象、传输及自定义处理器,绑定端口启动。自定义处理器处理消息和异常,可按需调整端口和完善业务逻辑。

Java + Netty 实现即时通讯 完整代码示例以及代码注释如下:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
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 io.netty.handler.codec.string.StringEncoder;

public class InstantMessagingServer {
    private int port;

    public InstantMessagingServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        // 创建两个EventLoopGroup,用于处理客户端连接和网络IO操作
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建ServerBootstrap对象,用于启动服务器
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup) // 设置两个EventLoopGroup
                    .channel(NioServerSocketChannel.class) // 指定使用NIO传输Channel
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加StringDecoder和StringEncoder,用于处理字符串消息的编解码
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            // 添加自定义的处理器
                            ch.pipeline().addLast(new InstantMessagingServerHandler());
                        }
                    });

            // 绑定端口,启动服务器并等待绑定完成
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("Server started on port " + port);

            // 等待服务器的Channel关闭
            future.channel().closeFuture().sync();
        } finally {
            // 优雅地关闭EventLoopGroup
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        InstantMessagingServer server = new InstantMessagingServer(port);
        server.run();
    }
}

class InstantMessagingServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Received message: " + msg);
        ctx.writeAndFlush("Server received: " + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 发生异常时关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
在这个示例中,我们创建了一个InstantMessagingServer类来启动服务器。在run方法中,我们创建了两个NioEventLoopGroup来处理客户端连接和网络IO操作。然后,我们创建了一个ServerBootstrap对象,并设置了两个EventLoopGroup、使用NIO传输Channel和自定义的处理器。最后,我们绑定端口,启动服务器并等待绑定完成。
InstantMessagingServerHandler类是自定义的处理器,继承自SimpleChannelInboundHandler<String>。在channelRead0方法中,我们处理接收到的消息,并通过ctx.writeAndFlush方法将处理结果返回给客户端。在exceptionCaught方法中,我们处理发生的异常,并关闭连接。
注:可以根据需要调整服务器的端口号,以及在channelRead0方法中完善自己接收到的消息的业务逻辑,进行具体操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值