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 {
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
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);
future.channel().closeFuture().sync();
} finally {
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
方法中完善自己接收到的消息的业务逻辑,进行具体操作。