java - Creating the ServerSocket in a separate thread? -


I have a problem in using ServerSocket in my application.

I am creating ServerSocket in the constructure of my application. The manufacturer of the socket calls the accept () method to wait for the customer to call.

The problem is that accept () is the method until my client is connected and my whole application is cold. So I would like to ask whether there is an option to create whole ServerSocket in a separate thread, which is the constructor of ServerSocket and its accept () method Is called next to my main application?

Edit:

Thanks for Olivier, for the advice. Enter a runnable and create a threadpool to handle the client connection. / P>

My code is right now:

  Public Zero Starter () {Last Executor Service Customer Processing Pool = Examiner. NewfixedThreadPool (10); Runnable ServerTask = New Runnabel () {@ Override Public Wired Run (try {serverSocket = new ServerSocket (port); While (true) {socket client socket = serverSocket.accept (); Object = new object overputstream (client socket.getoutputput ()); ClientProcessingPool.submit (new customer task (client socket, objectout)); }} Hold (IOException e) {System.err.println ("accept accept."); }}};   

Everything is going fine! Thanks! Normally, I use N + 1 threads for this: one for ServerSocket, one for the server, The entire application is waiting for a customer to connect to avoid blocking; And to process N Threads client requests, the size of the N-Thread Pool (I recommend using a thread pool to create a new thread for a client).

Here is an example (it has been coded, maybe a better exception management and so on, but this is a minimal work example)

  public Class server {public static zero main (string [] args) {new server (). StartServer); } Public Zero Start Server () {Final Executor Services Employee Process = Examiner. Nephix and Paul (10); RunNible ServerTask = New Runnabel () {@ Override Public Wide Run (try {serverSocket serverSocket = new ServerSocket (8000)) System.out.println ("Waiting for client to connect ..."); While (true) {socket client socket = serverSocket.accept (); ClientProcessingPool.submit (new customer task); }} Hold (IOException e) {System.err.println ("Unable to process client request"); E.printStackTrace (); }}}; Thread servertrread = new thread (servertask); ServerThread.start (); } Private class ClientTask implements Runnabel {Private Final Socket Client Socket; Private clienttask (socket client socket) {this.clientSocket = clientSocket; } @ Override Public Wide Run () {System.out.println ("Found a customer!"); // Anything that is needed to process the client's request {clientSocket.close (); } Hold (IOException e) {e.printStackTrace (); }}}}    

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -