客户端代码:
package cn.alex;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(9092));
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("connected");
}
}
}
服务端代码
package cn.alex;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyIMServerApplication {
public void startServer() throws InterruptedException {
// 处理 accept事件
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
// 处理读写事件
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer<>() {
@Override
protected void initChannel(Channel channel) throws Exception {
System.out.println("init " + channel.id());
}
});
Runtime.getRuntime().addShutdownHook(new Thread(()->{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}));
ChannelFuture channelFuture = bootstrap.bind(9092).sync();
System.out.println("服务启动成功,监听端口为 9092");
// 这里会阻塞掉主线程,实现服务长期开启
channelFuture.channel().closeFuture().sync();
}
public static void main(String[] args) throws InterruptedException {
NettyIMServerApplication application = new NettyIMServerApplication();
application.startServer();
}
}
谢谢老师