Reputation: 51
I trying to create multithreaded server, which will receive messages from different clients and then sends messages back. I am using execute server to manage the creations of
threads. But i am not sure if i'm doing it wright, i haven't used executor service before? And i have problem with this line
executor.execute(new Handler(client));
handler is abstract, cannot be initialized? How to fix it? Will execute service solve problem with binding ports? will it make smth like queue of client's of requests? thx in advance
package serverx;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Handler;
public class ServerX {
public static void main(String [] args){
ExecutorService executor = Executors.newFixedThreadPool(30);
ServerSocket server;
try{
server= new ServerSocket(5555);
System.out.println ("Server started!");
while(true) {
try{
Socket client = server.accept();
//Thread t= new Thread (new Handler(client));
//t.start();
executor.execute(new Handler(client));
}
catch (IOException e) {
e.printStackTrace();
}
}
}catch (IOException el){
el.printStackTrace();
}
}
}
Handler:
public class Handler implements Runnable{
private Socket client;
public Handler(Socket client){
this.client=client;}
public void run(){
//............
}
}
Upvotes: 1
Views: 3283
Reputation: 1355
Your handler must not be abstract. Make your handler class inner and define your client socket outside of the while loop.
Socket client;
while(true) {
try{
client = server.accept();
executor.execute(new Handler(client));
}
I want to add more about your question ;
ExecutorService is very good at controlling number of threads. Also you can define your number of threads like that if "30" is not your requirement. :
int poolSize = 50 * Runtime.getRuntime().availableProcessors();
ExecutorService tasks = Executors.newFixedThreadPool(poolSize);
In a multithreaded server, each time a client connects, server creates a new thread and this thread works for this client's job. Thats why you would define this thread as inner class and implements runnable interface.
Upvotes: 2