My teacher showed us code to implement an application server multithread but I am a little bit confused. is this an implementation of a multithread server? I didn’t understand if it’s so.
We suppose to create an object Server s = new Server(port_number). Could we assert it is a multithread server ?
import java.io.*;
import java.net.*;
public class Server implements Runnable
{
private ServerSocket serverSocket;
public MainCenterServer(int port){
try
{
this.serverSocket = new ServerSocket(port);
}
catch(IOException ioe) {ioe.printStackTrace(); }
new Thread(this, "Server").start();
}
@Override
public void run()
{
while(true)
{
try
{
Socket socket = serverSocket.accept();
}
catch(IOException ioe) {ioe.printStackTrace(); }
}
}
}
By your definition of a multithreaded server, yes, this server is multithreaded.
new Thread(this, "Server").start()creates a separate thread for therun()method to execute on. Since therunmethod has an infinite loop, it will always be waiting for a client to accept (Socket socket = serverSocket.accept()).