我正在处理一个简单的应用程序。 我想了解我的例外,但我不能。无法连接到Netty服务器两次
如何重现:
- 开始的Netty服务器
- 连接到服务器的Netty与客户端 - >有效的响应,服务器+客户端工作正常。
- 客户端关闭(0激活通道,通过调试线程证明)
- 新的客户端试图读取 - >错误:java.net.SocketException异常:软件导致连接中止:recv的失败
- 重新启动服务器,转到2 。
Server源:
public class Server {
private final int port;
public Server(int port) {
this.port = port;
}
public void run() throws Exception {
final EventLoopGroup boss = new NioEventLoopGroup();
final EventLoopGroup worker = new NioEventLoopGroup();
try {
final ServerBootstrap b = new ServerBootstrap();
b.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childHandler(new SocketChannelInitializer());
final ChannelFuture f = b.bind(port).sync();
final ChannelFuture c = f.channel().closeFuture();
System.out.println("- DONE -");
c.sync();
} finally {
worker.shutdownGracefully();
boss.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new Server(port).run();
}
}
我Initialisizer:
public static final String PACKET = "packet";
public static final String STRING_DECODER = "stringDecoder";
public static final String NETWORK_HANDLER = "networkHandler";
@Override
public void initChannel(SocketChannel ch) throws Exception {
System.out.println("Creating new Channel!");
final ChannelPipeline p = ch.pipeline();
p.addLast(NETWORK_HANDLER, new NetworkHandler());
p.addLast(STRING_DECODER, new StringDecoder(CharsetUtil.UTF_8));
p.addLast(new Testdecoder());
p.addLast(new ChatAdapter());
}
服务器DOES处理请求,但它不能读取正确的消息。
我的客户:
public static void main(String[] args) throws IOException {
final Socket s = new Socket();
s.connect(new InetSocketAddress("localhost", 8080));
final InputStream is = s.getInputStream();
final OutputStream os = s.getOutputStream();
os.write(0x0);
os.write("username".getBytes(CharsetUtil.UTF_8));
os.flush();
System.out.println("!");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[4096];
while (true) {
int n = is.read(b);
if (n < 0) {
break;
}
baos.write(b, 0, n);
}
byte data[] = baos.toByteArray();
System.out.println(new String(data, CharsetUtil.UTF_8));
System.out.println("- DONE -");
s.close();
}
使用的Netty 4.0.23.Final
示例应用: https://github.com/BjoernAkAManf/Chat
启动Server.main(字串[] args),然后运行Client.main( String [] args)两次。您将首先获得正确的输出。第二次运行将失败。 我测试了我可能想到的任何东西。真的很感谢这里的帮助。谢谢
Downvoting没有任何评论。这很不错。我试图自己调试整个程序,几天工作相当辛苦 - 我不是故意冒犯任何人,但如果你冷静地提出问题,至少告诉我原因 - 这个问题很容易重现,只需自己测试一下。如果问题与我的处理程序有某种关系,则会在某处抛出或打印异常。在我的逻辑中必然存在一个缺陷 - 以前没有人报告过这个问题,我在这里使用马厩。 – manf 2014-10-22 19:36:06