Thursday, November 2, 2017

SOCKET PROGRAMMING (TCP) - 19-11-17

Client must contact server
  • Server process must first be running
  • Server must have created socket (door) that welcomes client’s contact
Client contacts server by:
  • Creating client-local TCP socket
  • Specifying IP address, port number of server process
  • When client creates socket: client TCP establishes connection to server TCP
CLIENT AND SERVER INTERACTION:
  1. The server binds a socket to a specific port number and starts waiting for clients.
  2. A client initializes a connection with the service specified by its host name and port number.
  3. The server accepts the connection made by the client and creates a new socket for communicating with it.
  4. From the point of view of the client it is (usually) the socket which was used to initialize the connection. 
DEFINITION : SOCKET
==========
  • A Socket is one endpoint of a two way communication link between two programs running on the network.
  • An Endpoint is a combination of an IP address and a port number.
  • A Socket is bound to a port number so that the TCP layer can identify the application that data is defined to be sent to
  • The client knows the hostname of the machine on which the server is running and the port number on which the server is listening
  • To make a connection request, the client tries to connect with the server on the Server's machine and port.
  • The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection.
COMMUNICATION USING SOCKETS:
The communication using the Sockets are done by using either TCP or UDP
  • Transmission Control Protocol (TCP)
  • User Datagram Protocl (UDP)
 
TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers. It guarantees that the sent data are not lost and arrive in the proper order to the receiver. 

UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP. Datagrams may arrive to the receiver in an arbitrary order, some of them might be lost. 

TCP service: reliable transfer of bytes from one process to another
A stream is a sequence of characters that flow into or out of a process.
  • An input stream is attached to some input source for the process, e.g., keyboard or socket.
  • An output stream is attached to an output source, e.g., monitor or socket


Server has two types of sockets: ServerSocket and Socket
  1. server sockets (the class ServerSocket) - used by servers,
  2. client sockets (the class Socket) - used by clients; servers use it too for communication with clients.
TCP SERVER: 
  • The server accepts the connection and the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client.
[SERVER-PORT-LISTENER]<------- Connection Request <-----[PORT-CLIENT]

[SERVER-PORT-LISTENER]-------- Connection ------------->[PORT-CLIENT]




TCP Server communicates with a TCP Client
TCP CLIENT
  • On the Client side, if the connection is accepted, a Socket is successfully created and the client can use the socket to communicate with the server. 
  • The Client and Server can now communicate by writing to or reading from thier sockets. 
  • Every TCP connection can be uniquely identified by its two endpoints. So, you can have multiple connections between your host and server 
  • import java.net.*; package in the java platform provides a class, 'SOCKET', that implements one side of a two way connection between your java program and another program on the network. 
  • The 'Socket' class sits on top of a platform-dependent implementation, hiding the details of any particular system from your java program. 
  • 'SERVERSOCKET' class implements a socket that servers can use to listen for and accept connection to clients.
Clients Side Communication : STEPS
When programming a client, you must follow these four steps:
  1. Creating a new socket
  2. Declaring a message
  3. Obtaining streams associated with the socket (OutputStream and ObjectOutputStream)
  4. writeObject to send message
  5. Closing streams
  6. Closing the socket

1. Create a new socket 

         Socket skt = new Socket("127.0.0.1", 6999);

         System.out.println("Connected to server");


The Socket class constructor takes two parameters – a string, the IP address of the server and an integer, the port number on the server which the client would like to connect. 127.0.0.1 is the default address of the local system in computer networks.

    Socket Socket_name = new Socket("Machine name", PortNumber);
    Eg. Socket skt = new Socket("127.0.0.1", 6999);
 

Note:
  • Machine name is the machine you are trying to open a connection to, and Port number is the port (a number) on which the server you are trying to connect to is running.
  • The Port numbers between 0 to 1023 are reserved for provileged users (that is super user or root). They are used for standard services such as email, FTP, and HTTP

2. Declaring a message

This message is sent to the server from client         
      Eg. String msg = "Hello Server";

3. Output Stream
The getOutputStream() method of Socket class returns an object of OutputStream, here the object is os. This is the starting point of the whole communication (program). Here, the socket gets linked to streams. Streams are instrumental to pass the data.
OutputStream OutputStream_name = Socket_name.getOutputStream();
        Eg.  OutputStream os = skt.getOutputStream();   

4. DataOutputStream
As OutputStream is an abstract class; it cannot be used directly. In the above code, it is chained to a concrete class DataOutputStream.
ObjectOutputStream ObjectOutputStream_name = new ObjectOutputStream(OutputStream_name);

         Eg. ObjectOutputStream oos = new ObjectOutputStream(os);

5. writeObject to send message

writeBytes() method of DataOutputStream takes the string message and passes to the Socket. Now the client socket sends to the other socket on the server. When the job is over close the streams and socket. It releases the handles (links) connected to the system resources.
  • ObjectOutputStream_name.writeObject(msg);         
Eg.    oos.writeObject(msg);

 

6. Closing the Streams
The ObjectOutputStream and OutputStreams are to be closed as follows:

         oos.close();

         os.close();



7. Closing the Socket
Finally, the Socket which is used  should be closed at the end.

         skt.close();
 
SERVER SIDE COMMUNICATION : STEPS
1. Creating a new Server Socket
2. Accepting a connection from Client on Server
3. Creating Streams (InputStream and ObjectInputStream)
4. Reading message (readObject)
5. Closing Streams 
6. Closing the Socket (Server and Client)

1. Creating a new Server Socket
           The server has two jobs – one is, as expected, to communicate and the other is binding the connection on the port number 5000. For communication, it uses Socket and for binding, it uses ServerSocket. Binding is nothing but dedicating the port number to the client as long as it would like; meantime, if some other client asks for 5000 port number, it should not be alloted by the server. When client disconnects, the port is freed and can be given to another client by the server.
  • ServerSocket ServerSocket_name = new ServerSocket(PortNumber);
         Eg. ServerSocket ss = new ServerSocket(6999);

2. Accepting a connection from Client on Server
          accept() is a method of ServerSocket class used, used by the server, to bind the connection on the port number 5000, requested by the client. 
While implmenting a server youal so need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.
  • Socket Socket_name == ServerSocket_name.accept();
  • Eg. Socket skt = ss.accept();
3. Creating Streams (InputStream and ObjectInputStream)
getInputStream() method of Socket returns an object of InputStream and this is the starting point on the server program. The server uses input stream as it is receiving the message.  
  • InputStream InputStream_name = Socket_name.getInputStream();
            Eg. InputStream is = skt.

As InputStream is an abstract class, it cannot be used directly. It is chained to a concrete class ObjectInputStream.  
  •  ObjectInputStream ObjectInputStream_name = new ObjectInputStream(InputStream_name);
Eg. ObjectInputStream ois = new ObjectInputStream(is);


4. readObject() method - to read message

readObject(0 method of ObjectInputStream reads the message string from the socket and returns. This message is printed at the console.  
  • Datatype Variable_name = (Datatype)ObjectInputStream_name.readObject();
            Eg. String msg = (String)ois.readObject();

5. Display the Message
System.out.println("Server recieved message : " + msg);
System.out.println("Server is exiting ... ");
6. Closing Streams 
The ObjectInputStream and InputStream are closed

        Eg. ois.close();
                is.close();


7. Closing the Socket  (Server and Client)
Finally, Client Socket and ServerSocket are closed.
Eg. skt.close();
      ss.close();

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.