帮忙用netty写一个服务端,不要main启动的
时间: 2024-03-01 20:51:40 浏览: 84
服务端Netty搭建
5星 · 资源好评率100%
好的,下面是一个使用Netty框架编写服务端的示例代码,不使用main方法启动:
```java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
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 NettyServer {
private final int port;
public NettyServer(int port) {
this.port = port;
}
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new StringEncoder());
socketChannel.pipeline().addLast(new NettyServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
System.out.println("Server started on port " + port + ".");
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
```
上述代码中,我们将启动代码封装到了start方法中,并且在构造函数中传入了服务端的端口号。在start方法中,我们仍然创建了ServerBootstrap实例,并且设置了bossGroup和workerGroup,以及通道类型和处理器。最后,我们调用bind方法绑定服务器的端口号,并且调用sync方法等待服务器启动,然后调用channelFuture.channel().closeFuture().sync()方法等待服务器关闭。
在实际使用时,我们可以在其他类中创建NettyServer实例,并且调用start方法启动服务器。例如:
```java
public class MyApp {
public static void main(String[] args) throws Exception {
NettyServer server = new NettyServer(8888);
server.start();
}
}
```
这样就可以启动一个监听在8888端口的Netty服务器了。
阅读全文