Java Socket Programming – Part 1

Here is a simple socket programming which allows a client to be connected to a server using Java. Lets create a simple file transfer from a client machine to the server.

  1. First make a connection with the server
  2. If the connection was successful, open a text file (in the client’s machine)
  3. Send the file to the server

The following code will be used for client

/**
 * Socket programming  using  Java
 * A client to server connection
 */

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

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

    // open a port for connection
    short portnumber = 7777; // assuming your own port
    String hostname, fileName;
    OutputStream os = null;

    // get hostname or ip address of the server
    BufferedReader host = new BufferedReader( new InputStreamReader ( System.in ));
    System.out.print("Enter the server name: ");
    hostname = host.readLine();

    // define client socket object
    Socket clientSocket = null;
    try {
      clientSocket = new Socket( hostname, portnumber );
      System.out.println("Connecting to " + hostname + " on port " + portnumber + "...");
    } catch ( UnknownHostException e ) {
      System.out.println("Unknown server : " + e.getMessage());
      System.exit(1);
    } catch ( IOException e ) {
      System.out.println(e.getMessage());
    }

    // send file to server
    if (clientSocket != null ) {
      System.out.println("Connection accepted");
      BufferedReader fileBr = new BufferedReader( new InputStreamReader ( System.in ));

      // open file for transfer
      System.out.print("Enter the name of the text file you want to sent: ");
      fileName = fileBr.readLine();
      File myTextFile = new File (fileName);

      // open file stream for sending bytes of data
      byte [] buffer  = new byte [(int)myTextFile.length()];
      try {
        FileInputStream fin = new FileInputStream(myTextFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read( buffer, 0, buffer.length);
        os = clientSocket.getOutputStream();
        System.out.println("Sending...");
        os.write(buffer, 0, buffer.length);
        os.flush();
        System.out.println("File was send sucessfully!");
      } catch ( IOException e ) {
        System.out.println("File not found!");
      } finally {
        clientSocket.close();
      }
    } else {
      System.out.println("Connection failed!");
      System.exit(1);
    }
  }
}
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