Base class to build multithreaded servers easily : Server « Network Protocol « Java






Base class to build multithreaded servers easily

  
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

class MTServerBase extends Thread {
  protected Socket socket;

  public void run() {
    try {
      String s = "Server.";
      socket.getOutputStream().write(s.getBytes());
      socket.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  static public void startServer(int port, Class clobj) {
    ServerSocket ssock;
    Socket sock;
    try {
      ssock = new ServerSocket(port);
      while (true) {
        Socket esock = null;
        try {
          esock = ssock.accept();
          MTServerBase t = (MTServerBase) clobj.newInstance();
          t.socket = esock;
          t.start();
        } catch (Exception e) {
          try {
            esock.close();
          } catch (Exception ec) {
          }
        }
      }
    } catch (IOException e) {
    }
  }
}

public class UCServer extends MTServerBase {

  public void run() {
    try {
      InputStream is = socket.getInputStream();
      OutputStream os = socket.getOutputStream();
      while (true) {
        char c = (char) is.read();
        // end on Control+C or Control+D
        if (c == '\003' || c == '\004')
          break;
        os.write(Character.toUpperCase(c));
      }
      socket.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) {
    int n = Integer.parseInt(args[0]);
    System.out.println("Starting server on port " + n);
    startServer(n, UCServer.class);
  }
}


           
         
    
  








Related examples in the same category

1.A generic framework for a flexible, multi-threaded server
2.Server allows connections on socket 6123Server allows connections on socket 6123
3.This server displays messages to a single clientThis server displays messages to a single client
4.The client can specify information to control the output of a serverThe client can specify information to control the output of a server
5.A server can use specialized streams to deliver typed dataA server can use specialized streams to deliver typed data
6.Serve entire objects using ObjectOutputStreamServe entire objects using ObjectOutputStream
7.A multithreaded serverA multithreaded server
8.Manage a pool of threads for clients
9.Client estimates the speed of the network connection to the server
10.This server retrieves the time using the RFC867 protocol.This server retrieves the time using the RFC867 protocol.
11.Quote Server
12.Logging Server based on SocketServer
13.Client and Server Demo
14.Reflector
15.Simple Http Server