问题描述
- Netty 服务器绑定的端口有误
-
本人刚接触Netty/java。遇到一个纠结了我一天的问题,不知道是怎么处理的,特上来求教各位大牛,
分数可能不多,但是真心求大神们解决!
问题是这样的,我用的是Netty2.3.5版本。
服务器端的ServerBootstrap对象绑定bind(9002) 9002端口号。
客户端bootstrap.connect(new InetSocketAddress("124.232.147.45", port),new InetSocketAddress(9001));明明指明了是9001调用服务器的9000端口,但是部署在服务器后,绑定的不是9001端口,而是服务器随机分配的一个。
代码如下:(服务器)Executor executor = Executors.newCachedThreadPool();
ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(executor,executor));
//ClientSocketChannelFactory cf = new NioClientSocketChannelFactory(executor, executor);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("encode", new StringEncoder());
pipeline.addLast("decode", new StringDecoder());
pipeline.addLast("handler", new ChatServerHandler());
return pipeline;
}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("child.reuseAddress", true);
bootstrap.bind(new InetSocketAddress(9000)) // 绑定端口;客户端
private final static int port=9000;
ClientBootstrap bootstrap;
ChatClientHandler handler;
ChannelFuture channelFuture;
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline channelPipeline = Channels.pipeline();
channelPipeline.addLast("encode", new StringEncoder());
channelPipeline.addLast("decode", new StringDecoder());
channelPipeline.addLast("handler", handler);
return channelPipeline;
}
});
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
bootstrap.setOption("reuseAddress", true);
bootstrap.connect(new InetSocketAddress("124.232.147.45", port),new InetSocketAddress(9001));// 就这里,我明明指明了是9001端口,服务器端打印的确是其他的端口,如果124.232.147.45换成127.0.0.1,把本机作为服务器,局域网上的另外一台机器作为客户端,那么端口是对的,是9001端口。如果我把服务器部署在服务器上,接着客户端也部署在另外的服务器上面,绑定的端口有事正确的。这是为什么呢?
解决方案
从新试着绑定一下9001端口呢?
解决方案二:
客户端端口一般都是随机的