Multithreading Java Server


Multithreading Java server Server.java

 

 

    import java.io.*;
    import java.net.*;
    
    
    
    //The Server class creates a ServerSocket to listen to
    // port number 50001.  When a client tries to connect at
    //this port is creates an instance of the Service class
    //to handle communications with this client.  This class
    // is a thread that is started.  Each new client will get a
    // new thread.
    
    public class Server {
      public static void main(String argv[]) throws Exception { 
        try {
          ServerSocket socket = new ServerSocket(50001, 100);
          while ( true )
            new Service(socket.accept()).start(); //create and start thread
    
        } catch ( IOException e ) {
          System.err.println("IOException: " + e.getMessage());
        }
      }
    }
    
    
    
    //This class is a Service class that is a Thread.  It handles
    //requests between a particular Client that opened a Socket to
    //This server.
    //This Service class simply expects the client to send the name of
    //a file and then it opens up this file on the server and sends
    //down the data to the client over the open Socket.
    class Service extends Thread {
      Socket client;
    
      public Service(Socket client) { this.client = client; }
        
      public void run() {
        byte[] buf = new byte[1024]; 
        int c, i = 0;
        try {
          InputStream  in  = client.getInputStream(); 
          OutputStream out = client.getOutputStream();
          do { c = in.read();          // read filename from socket
               buf[i++] = (byte)c;
          } while ( c != 10 );
          String name = new String(buf, 0, i).trim();
          FileInputStream file = new FileInputStream(name);
          do { i = 0;
               do { c = file.read();   // load buffer from file
                    buf[i++] = (byte)c;
               } while ( i < 1023 && c != 10 && c != -1 );
               out.write(buf, 0, i);   // write buffer down socket
          } while ( c != -1 );
          file.close();
          out.flush();
          client.close();
        } catch ( IOException e ) {
          System.err.println("IOException: " + e.getMessage());
        }
      }
    }