Java multithreaded server - each connection returns data. Processing on main thread?
Posted
by
oliwr
on Stack Overflow
See other posts from Stack Overflow
or by oliwr
Published on 2010-12-22T07:00:06Z
Indexed on
2010/12/23
9:54 UTC
Read the original article
Hit count: 398
I am writing a client with an integrated server that should wait indefinitely for new connections - and handle each on a Thread.
I want to process the received byte array in a system wide available message handler on the main thread. However, currently the processing is obviously done on the client thread.
I've looked at Futures, submit() of ExecutorService, but as I create my Client-Connections within the Server, the data would be returned to the Server thread. How can I return it from there onto the main thread (in a synchronized packet store maybe?) to process it without blocking the server?
My current implementation looks like this:
public class Server extends Thread {
private int port;
private ExecutorService threadPool;
public Server(int port) {
this.port = port;
// 50 simultaneous connections
threadPool = Executors.newFixedThreadPool(50);
}
public void run() {
try{
ServerSocket listener = new ServerSocket(this.port);
System.out.println("Listening on Port " + this.port);
Socket connection;
while(true){
try {
connection = listener.accept();
System.out.println("Accepted client " + connection.getInetAddress());
connection.setSoTimeout(4000);
ClientHandler conn_c= new ClientHandler(connection);
threadPool.execute(conn_c);
} catch (IOException e) {
System.out.println("IOException on connection: " + e);
}
}
} catch (IOException e) {
System.out.println("IOException on socket listen: " + e);
e.printStackTrace();
threadPool.shutdown();
}
}
}
class ClientHandler implements Runnable {
private Socket connection;
ClientHandler(Socket connection) {
this.connection=connection;
}
@Override
public void run() {
try {
// Read data from the InputStream, buffered
int count;
byte[] buffer = new byte[8192];
InputStream is = connection.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
// While there is data in the stream, read it
while ((count = is.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
is.close();
out.close();
System.out.println("Disconnect client " + connection.getInetAddress());
connection.close();
// handle the received data
MessageHandler.handle(out.toByteArray());
} catch (IOException e) {
System.out.println("IOException on socket read: " + e);
e.printStackTrace();
}
return;
}
}
© Stack Overflow or respective owner