简体   繁体   中英

tcp multithreaded server java

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(){
         //............   

    }

}

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.

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