简体   繁体   中英

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.

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:

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:

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? I tried only passing the Sockets in the ThreadManager constructor and then creating new BufferedReader... etc. but this seems to be just as bad. Could anyone suggest either the solution, or where the problem lies (or both!) :) thanks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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