简体   繁体   English

Java将BufferedReader,DataOutputStream和Sockets传递给可运行的线程类会导致在写入流时导致套接字异常

[英]Java passing BufferedReader, DataOutputStream and Sockets to a runnable thread class leads to socket exception upon writing to stream

I have two 'Client's, one 'Server' and potentially a 'ThreadManager' that implements runnable. 我有两个“客户端”,一个“服务器”,可能还有一个实现可运行的“ ThreadManager”。

The two Clients connect with Server via TCP and partake in a protocol handshake/ authentication thing (successful), then I attempted to pass the existing BufferedReaders, DataOutputStreams and Sockets to 'ThreadManager' to manage threading messages between Client1 and Client2: 这两个客户端通过TCP与Server连接,并参与了协议握手/身份验证(成功),然后我尝试将现有的BufferedReader,DataOutputStreams和Sockets传递给“ ThreadManager”,以管理Client1和Client2之间的线程消息:

SERVER: 服务器:

ThreadManager tManager = new ThreadManager(serviceToClient1,  inputStream, outputStream, serviceToClient2, inputStream2, outputStream2);
new Thread(tManager).start();
serviceToClient1.close();
serviceToClient2.close();

THREADMANAGER: 线程管理器:

public ThreadManager(Socket cli1, BufferedReader inputStream, DataOutputStream outputStream, Socket cli2, BufferedReader inputStream2, DataOutputStream outputStream2)
{
this.cli1 = cli1;
this.inputStream = inputStream;
this.outputStream = outputStream;
this.cli2 = cli2;
this.inputStream2 = inputStream2;
this.outputStream2 = outputStream2;
}

this constructs successfully, however on .start() called from Server, debugging shows a "Socket Exception: Socket Closed" error as soon the following is called from within ThreadManager: 这可以成功构造,但是在从Server调用的.start() ,一旦从ThreadManager中调用以下命令,调试就会显示“套接字异常:套接字关闭”错误:

outputStream.writeBytes("NUMBER: " + i + "\n");

I'm not sure where the problem is created, would I need to close connections and recreate Sockets and streamreaders/writers from within ThreadManager? 我不确定问题出在哪里,我是否需要关闭连接并从ThreadManager中重新创建Socket和streamreaders / writer? I tried only passing the Sockets in the ThreadManager constructor and then creating new BufferedReader... etc. but this seems to be just as bad. 我尝试仅在ThreadManager构造函数中传递Socket,然后创建new BufferedReader... etc.但这似乎也很糟糕。 Could anyone suggest either the solution, or where the problem lies (or both!) :) thanks. 任何人都可以提出解决方案,或者问题出在哪里(或两者都有!):)谢谢。

在尝试从Thread上读取Socket之前,请先关闭Socket ,以免发生异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM