Getting started with Socket programming in java

So you want to get started with socket programming in java.
Here is all you need to know to get started with socket programming in java.

For socket programming, there are two terms, called 'server' and 'client'.
  • 'Server' is one that will accept the request and send some response.
  • The client is one which will create request and send it to the server then receive the response came from the server.

Now, let's see a small example that can explain the basic scenario of client-server system (network programming). (You can skip the example. If you are aware of it.)

Example:
In a restaurant, there is a waiter and you, who is a customer. You came to the restaurant for dinner. Now you called the waiter to place an order. So the waiter came to you and took your order then severed your tasty dinner on the table.

Now, what is this example? WHY this.


Let's see again,
Say, the waiter is a server, the customer is client, the order is request and served food is response.
  • Now waiter(server) should always be in listening mode, i.e. he should be always available for the customer to listen to his request.
  • Now the customer(client) will call the waiter. (establish a connection with the server). 
  • Then the customer(client) will give order to the waiter. ( client will request to the server).
  • Waiter(server) will process the order and serve food to customer(client). (Server will process and send a response to the client)
Thus, for these, all communication waiter must be available from the beginning and should be in listening mode.
Now the customer will come, establish connection, request to the waiter and get the response.

So, it's done, now lets come to our code which we really want.

Server

To create a code of server we will follow these steps:
  1. Create a server socket.
  2. Bind it to a port.
  3. Put the server socket in listening mode.
  4. Get the reference of 'inputstream'.
  5. Attach it to 'inputstreamreader'.
  6. Read and put in buffer.
  7. Parse and process.
  8. Generate output.
  9. Get the reference of 'outputstream'.
  10. Attach it to the 'outputstreamwriter'.
  11. writer and flush.
  12. close connection.
Code to create a server using socket programming:

MyServer.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import java.net.*;
import java.io.*;

class MyServer {
    private ServerSocket serverSocket;
    private int portNumber;

    MyServer(int portNumber) throws Exception {
        this.portNumber = portNumber;
        // Step 1: create server socket
        // Step 2: bind it to the port on which it is going to listen reauest
        serverSocket = new ServerSocket(portNumber);
        // Put the server socket in listening mode
        startListening();
    }

    public void startListening() {
        try {
            InputStream is;
            InputStreamReader isr;
            OutputStream os;
            OutputStreamWriter osw;
            StringBuffer sb;
            int c1, c2;
            int rollNumber;
            String name, gender;
            String pc1, pc2, pc3;
            int x;
            Socket socket;
            String request, response;
            while (true) {
                /*
                 * Step 3: Put Server in listening mode .
                 * Due to below mentioned line the server will go in listening mode. 
                 * We have created a infinite loop to make server running state always.
                 * Because of accept() method the application will remain hold until
                 * a request arrives from client. When request comes it will be handled by
                 * accept method and this request will be diverted to another socket. The
                 * reference of that socket will be returned by accept method. We took reference
                 * of new socket created in socket variable.
                 */
                socket = serverSocket.accept(); // server will go in listening mode
                System.out.println("Request arrived");
                // Step 4: Get the refernce of inputstream
                is = socket.getInputStream();
                // Step 5: Attach the inputStream to inputStreamReader
                isr = new InputStreamReader(is);
                // create a string buffer to store the string, arriving in request
                sb = new StringBuffer();
                // this is infinite loop to accept requested string character by character
                while (true) {
                    // Step 6: read and put string in buffer
                    // read method will return the character of string coming in request
                    // if x is -1 means the request string is over so break the loop.
                    x = isr.read();
                    if (x == -1)
                        break;
                    // # is string terminator that we have created.
                    // Because the code of client will be written by us
                    // so we will send # in last from client.
                    if (x == '#')
                        break;

                    // append the received characters in buffer
                    sb.append((char) x);
                }
                // Get the whole request string from string buffer
                request = sb.toString();
                System.out.println("Request : " + request);
                /*
                 * Step 7: parse and process.
                 * Sample request: 101,Ambarish,M#
                 * Parsing of request is on the basis of comma. 
                 * Client will send the request string as details(name,rollNumber,gender) 
                 * of user by making a comma separated string.
                 * Now on server side we accepted string and then parsing it
                 * and extracting rollNumber,name,gender
                 */
                c1 = request.indexOf(",");
                c2 = request.indexOf(",", c1 + 1);
                pc1 = request.substring(0, c1);
                pc2 = request.substring(c1 + 1, c2);
                pc3 = request.substring(c2 + 1);
                rollNumber = Integer.parseInt(pc1);
                name = pc2;
                gender = pc3;
                // ---parsing ends and we got the below data from client
                System.out.println("Data received ");
                System.out.println("Roll number : " + rollNumber);
                System.out.println("Name : " + name);
                System.out.println("Gender : " + gender);

                // Here will be code to process data came in request

                // we will send the below string in response
                // Step 8: Generate output
                response = "Data Saved#";
                // Step 9: Get the reference of outputstream
                os = socket.getOutputStream();
                // Step 10: attach outputstream to outputstreamreader
                osw = new OutputStreamWriter(os);
                // Step 10: Write and flush
                // write the response
                osw.write(response);
                // Flush to send response to client
                osw.flush();
                System.out.println("Response sent : " + response);
                // Step 11: close connection
                // We will close the socket created by server
                socket.close();
            }
        } catch (Exception ee) {
            System.out.println(ee);
        }
    }

    public static void main(String gg[]) {
        int portNumber = 5000;
        System.out.println("Starting server on port : " + portNumber);
        try {
            MyServer server = new MyServer(portNumber);
            System.out.println("Server is ready and is listening on port : " + portNumber);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}


We have successfully created the server now its time to create a client.

Client

Steps to create client code:
  1. Create a request 
  2. Create a socket and specify the host and the port number of the server.
  3. Connect it to the server
  4. Get the reference of 'outputstream'.
  5. Attach it to the 'outputstreamwriter'.
  6. writer and flush.
  7. Get the reference of 'inputstream'.
  8. Attach it to 'inputstreamreader'.
  9. Read and put in buffer.
  10. Parse and process.
  11. Generate output.
Code to create a client:

MyClient.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.io.*;
import java.net.*;
class MyClient {
  public static void main(String gg[]) {
    try {

      // Lets take roll number,name, gender from command line
      int rollNumber = Integer.parseInt(gg[0]);
      String name = gg[1];
      String gender = gg[2];
      // Step 1:Create request
      /*
       * We have created the request with separator as comma and on server side this
        * request will be parsed. Here we have put # at the end of string to specify
        * that our data string has been end. We can take any symbol which has not been
        * used as valid data to be sent on server side

       */

      String request = rollNumber + "," + name + "," + gender + "#";
      // Our server is running at 5000 and host is 'localhost'
      String server = "localhost";
      int serverPort = 5000;
      System.out.println("Establishing connection with " + server + " listening on port " + serverPort);
      // Step 2: Create socket and specify the server host and port number
      // Step 3: connect it to server socket
      /*
        * By creating object of socket and passed it the ip(host) and port number of
         * server we have established a connection with server
        */

      Socket socket = new Socket(server, serverPort);

      // Step 4:Get the reference of outputstream
      OutputStream os = socket.getOutputStream();

      // Step 5:Attach it to outputStreamWriter
      OutputStreamWriter osw = new OutputStreamWriter(os);
      System.out.println("Sending request : " + request);
      // Step 6: write the request and flush
      osw.write(request);
      osw.flush();

      // Step 7: Get the reference of inputStream
      InputStream is = socket.getInputStream();

      // Step 8: Attach it to inputStreamReader
      InputStreamReader isr = new InputStreamReader(is);
      // Step 9: read and put in buffer
      // create a buffer to accept the string of response coming from server
      StringBuffer sb = new StringBuffer();
      int x;

      /*

       * Same infinite loop as we created on server,here to accept response string coming from server

       */

      while (true) {
        x = isr.read();
        if (x == -1) break; // this won't happen in our case
        if (x == '#') break;
        sb.append((char) x);
      }

      // Step 10: Parse and process
      String responseReceived = sb.toString();

      // Step 11: Generate output
      System.out.println("Response received : " + responseReceived);

      // Step 11: close socket
      socket.close();

    } catch(Exception ee) {
      System.out.println(ee);
    }
  }
}







Now compile both server and client code.
Use command:
javac MyServer.java
javac MyClient.java

Now open two command prompts.
On first command prompt start server: java MyServer
When you will start the server you will see this:-


Now on another command prompt start client:
For that you will have to provide three command-line arguments rollNumber, name, gender which we want to send to server:

java MyClient 101 Ambarish M

I provided 101, Ambarish,M these three but you can take any other also.
When you will start client, the client code will send a request to server and output on both client and server will look like this:

On client:


On Server:


So you have finally created client-server using java socket programming.


Comments

Popular posts from this blog

PROJECT 1 DerbyDB Creator -SQL scripting tool for Apache Derby

PROJECT-2 Picture Modifier

Java Data Base Connectivity (JDBC) with MongoDB