Generic Server : ServerSocket « Network « Java Tutorial






import java.io.BufferedOutputStream;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class GenericServer {
   public static void main(String args[]) {
    int serverPort = 1234;
    try {
      ServerSocket server = new ServerSocket(serverPort);
      do {
        Socket client = server.accept();
        (new ServerThread(client)).start();
      } while (true);
    } catch (IOException ex) {
      System.exit(0);
    }
  }
}

class ServerThread extends Thread {
  Socket client;

  public ServerThread(Socket client) {
    this.client = client;
  }

  public void run() {
    try {
      ServiceOutputStream outStream = new ServiceOutputStream(new BufferedOutputStream(client
          .getOutputStream()));
      ServiceInputStream inStream = new ServiceInputStream(client.getInputStream());
      ServiceRequest request = inStream.getRequest();
      while (processRequest(outStream)) {
      }
      client.close();
    } catch (IOException ex) {
      System.exit(0);
    }
  }

  public boolean processRequest(ServiceOutputStream outStream) {
    return false;
  }
}

class ServiceInputStream extends FilterInputStream {
  public ServiceInputStream(InputStream in) {
    super(in);
  }

  public ServiceRequest getRequest() throws IOException {
    ServiceRequest request = new ServiceRequest();
    return request;
  }
}

class ServiceOutputStream extends FilterOutputStream {
  public ServiceOutputStream(OutputStream out) {
    super(out);
  }
}

class ServiceRequest {
}








19.14.ServerSocket
19.14.1.Create a ServerSocket
19.14.2.Hello Server
19.14.3.Time server
19.14.4.Thread based ServerSocket
19.14.5.Generic Server
19.14.6.Timer server with Thread
19.14.7.A multithreaded Socket Server
19.14.8.Get IP address from NetworkInterface and create server socket
19.14.9.Logging Server based on SocketServer
19.14.10.Data server
19.14.11.Object server
19.14.12.Compressed socket
19.14.13.Zip server socket