Java Socket Programming – Part II

In the second part, we need to have a server component that listens to client connections. This is a very basic demonstration of how clients connect to servers in the client-server architecture. In real world applications, we need to implement threads that listens to connections. Here is the code for the server side that runs in a single thread. We need to start the server component first so that it can receive client connections. If you change the port number, make sure you use the same port number for both modules.

/**
 * Socket programming  using  Java
 * Server component
 */

import java.io.*;
import java.net.*;
import java.util.*;

public class ServerDemo {
  public static void main( String args[] ) throws IOException {

    // open a port for connection
    short portnumber = 7777;   // assuming your own port
    int byteSize = 0, bufferSize = 0, filesize = 1048576; //max size - 1Mb

    FileInputStream fin = null;

    // define the server object
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket( portnumber );
      System.out.println("Waiting...");
      serverSocket.setSoTimeout(20000);   // set connection timeout
    } catch ( IOException e ) {
      System.exit(1);
    }

    // define client socket object
    Socket clientSocket = null;
    try {
      clientSocket = serverSocket.accept();
    } catch (SocketTimeoutException e) {
      System.out.println("Connection timed out!");
      System.exit(1);
    } catch ( IOException e ) {
      System.out.println("I/O error " + e);
      System.exit(1);
    }

    if (serverSocket != null ) {
      System.out.println("Connected to " + clientSocket.getInetAddress() + " on port "
        + clientSocket.getPort() + ", local port  " + clientSocket.getLocalPort());
      System.out.println("Waiting for request from " + clientSocket. getInetAddress());

      //create a new file to store incoming bytes
      byte [] buffer = null;
      InputStream in = null;
      String newfile = null;
      try {
        buffer  = new byte [filesize];
        in = clientSocket.getInputStream();
      } catch ( Exception e ) {
        System.out.println(e.getMessage());
      }      

      //open file stream for writing the contents of the file
      FileOutputStream fout = null;
      BufferedOutputStream bos = null;
      try{
        fout = new FileOutputStream("_temp~1.txt");
        byteSize = in.read( buffer, 0, buffer.length );
        bufferSize = byteSize;
      } catch ( Exception e ) {
        System.out.println(e.getMessage());
      }
      do {
        try {
          byteSize = in.read(buffer, bufferSize, ( buffer.length-bufferSize ));
          if(byteSize >= 0) {
            bufferSize += byteSize;
          }
        } catch (Exception e) {
          System.out.println("Error: Cannot receive file!");
          System.exit(1);
        }
      } while(byteSize > -1);

      try {
        bos = new BufferedOutputStream(fout);
        bos.write(buffer, 0, bufferSize);
        bos.flush();
        System.out.println("File received from " + clientSocket.getInetAddress());
        bos.close();
        fin = new FileInputStream("_temp~1.txt");

        //prompt for reading file
        String userInput = null;
        BufferedReader input = new BufferedReader( new InputStreamReader( System.in ));
        System.out.print("Do you want to display the contents of the file ? [y/n] : ");
        userInput = input.readLine();
        int i;
        if (userInput.equalsIgnoreCase("y")) {
          System.out.println();
          do {
            i = fin.read();
            if(i != -1) System.out.print((char) i);
          } while(i != -1); // read until end of file
        }
        in.close();
        fin.close();

        //prompt for saving file
        System.out.print("Do you want to save the file ? [y/n] : ");
        userInput = input.readLine();
        File f = null;
        f = new File("_temp~1.txt");
        if (userInput.equalsIgnoreCase("y")) {
          BufferedReader fileBr = new BufferedReader( new InputStreamReader ( System.in ));
          System.out.print("Specify a filename: ");
          newfile = fileBr.readLine();
          Boolean b = f.renameTo(new File(newfile));
          if( b )
            System.out.println("File successfully saved as \"" + newfile + "\"");
          else
            System.out.println("An error occured while saving file!");
        } else
          f.delete();
        in.close();
      } catch ( Exception e ) {
        System.out.println("Error : Could not save file!");
      } finally {
        serverSocket.close();
      }
    }
  }
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s