Introduction To Socket Programming: Practical - 02

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Component Technology(BTIT-505) Suyash Jain(1601DMBIT01011)

Practical – 02
INTRODUCTION TO SOCKET PROGRAMMING
 What is Socket?
A socket is a software object that acts as an end point establishing a bidirectional network
communication link between a server-side and a client-side program.A socket is one endpoint of a
two-way communication link between two programs running on the network. A socket is bound to
a port number so that the TCP layer can identify the application that data is destined to be sent to.
 What is Socket Programming?
Socket programming is a way of connecting two nodes on a network to communicate with each
other. One socket(node) listens on a particular port at an IP, while other socket reaches out to the
other to form a connection. Server forms the listener socket while client reaches out to the server.
On the client-side: 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 rendezvous 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. This is
usually assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, 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. It needs a new socket so that it can continue to listen to the original socket for
connection requests while tending to the needs of the connected 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 their sockets
 Why Socket Programming
Socket programs are used to communicate between various processes usually running on different
systems. It is mostly used to create a client-server environment. This post provides the various
functions used to create the server and client program and an example program. In the example,
the client program sends a file name to the server and the server sends the contents of the file back
to the client.
The client needs to learn two basic pieces of information, which are:
1. Port number
2. IP address of server
 Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.
The following figure shows a communication structure between two machines, in this figure, the
communication is done using a socket over the internet.

IT,SVIIT,Indore Page 1
Component Technology(BTIT-505) Suyash Jain(1601DMBIT01011)

Some commonly used public methods of the Socket class are:


1. synchronized void close()
2. Socket (String host, int port) thows UnknownHostException, IOException
3. Socket()
4. OutputStream getOutputStream()
5. InputStream getInputStream()
Stages for server:-
 Socket creation:-int sockfd = socket(domain, type, protocol)
sockfd :- socket descriptor, an integer (like a file-handle) domain:- integer, communication
domain e.g., AF_INET (IPv4 protocol) , AF_INET6 (IPv6 protocol) type:- communication type
SOCK_STREAM: TCP(reliable, connection oriented) SOCK_DGRAM: UDP(unreliable,
connectionless) protocol:- Protocol value for Internet Protocol(IP), which is 0. This is the same
number which appears on protocol field in the IP header of a packet.(man protocols for more
details)
 Setsockopt:-int sockfd, int level, int optname, const void *optval, socklen_toptlen);
This helps in manipulating options for the socket referred by the file descriptor sockfd. This is
completely optional, but it helps in reuse of address and port. Prevents error such as: “address
already in use”.
 Bind:-int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
After creation of the socket, bind function binds the socket to the address and port number
specified in addr(custom data structure). In the example code, we bind the server to the localhost,
hence we use INADDR_ANY to specify the IP address.
 Listen:-int listen(int sockfd, int backlog);
It puts the server socket in a passive mode, where it waits for the client to approach the server to
make a connection. The backlog, defines the maximum length to which the queue of pending
connections for sockfd may grow. If a connection request arrives when the queue is full, the client
may receive an error with an indication of ECONNREFUSED.
 Accept:-int new_socket= accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
It extracts the first connection request on the queue of pending connections for the listening
socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that
socket. At this point, connection is established between client and server, and they are ready to
transfer data.
Stages for client:-
 Socket creation:-int sockfd = socket(domain, type, protocol)
sockfd :- socket descriptor, an integer (like a file-handle) domain:- integer, communication
domain e.g., AF_INET (IPv4 protocol) , AF_INET6 (IPv6 protocol) type:- communication type

IT,SVIIT,Indore Page 2
Component Technology(BTIT-505) Suyash Jain(1601DMBIT01011)

SOCK_STREAM: TCP(reliable, connection oriented) SOCK_DGRAM: UDP(unreliable,


connectionless) protocol:- Protocol value for Internet Protocol(IP), which is 0. This is the same
number which appears on protocol field in the IP header of a packet.(man protocols for more
details)
 Connect :- int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
The connect() system call connects the socket referred to by the file descriptor sockfd to the
address specified by addr. Server’s address and port is specified in addr.
 How Socket Works:-
Sockets are commonly used for client and server interaction. Typical system configuration places
the server on one machine, with the clients on other machines. The clients connect to the server,
exchange information, and then disconnect.
A socket has a typical flow of events. In a connection-oriented client-to-server model, the socket
on the server process waits for requests from a client. To do this, the server first establishes
(binds) an address that clients can use to find the server. When the address is established, the
server waits for clients to request a service. The client-to-server data exchange takes place when a
client connects to the server through a socket. The server performs the client's request and sends
the reply back to the client.
1. The socket() API creates an endpoint for communications and returns a socket descriptor that
represents the endpoint.
2. When an application has a socket descriptor, it can bind a unique name to the socket. Servers
must bind a name to be accessible from the network.
3. The listen() API indicates a willingness to accept client connection requests. When a listen()
API is issued for a socket, that socket cannot actively initiate connection requests. The listen()
API is issued after a socket is allocated with a socket() API and the bind() API binds a name to the
socket. A listen() API must be issued before an accept() API is issued.
4. The client application uses a connect() API on a stream socket to establish a connection to the
server.
5. The server application uses the accept() API to accept a client connection request. The server
must issue the bind() and listen()APIs successfully before it can issue an accept() API.
6. When a connection is established between stream sockets (between client and server), you can
use any of the socket API data transfer APIs. Clients and servers have many data transfer APIs
from which to choose, such as send(), recv(), read(), write(), and others.
7. When a server or client wants to stop operations, it issues a close() API to release any system
resources acquired by the socket.
Client Side Programming
Establish a Socket Connection
To connect to other machine we need a socket connection. A socket connection means the two
machines have information about each other’s network location (IP Address) and TCP port.The
java.net.Socket class represents a Socket. To open a socket:

IT,SVIIT,Indore Page 3
Component Technology(BTIT-505) Suyash Jain(1601DMBIT01011)

Socket socket = new Socket(“127.0.0.1”, 5000)


 First argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where code
will run on single stand-alone machine).
 Second argument – TCP Port. (Just a number representing which application to run on a
server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)
Communication
getOutputStream() method is used to send the output through the socket.
To communicate over a socket connection, streams are used to both input and output the data.
Closing the connection
The socket connection is closed explicitly once the message to server is sent.
Server Programming
Establish a Socket Connection
To write a server application two sockets are needed.
 A ServerSocket which waits for the client requests (when a client makes a new Socket())
 A plain old Socket socket to use for communication with the client.
Communication
getOutputStream() method is used to send the output through the socket.
Close the Connection
After finishing, it is important to close the connection by closing the socket as well as
input/output streams.

Code:

IT,SVIIT,Indore Page 4
Component Technology(BTIT-505) Suyash Jain(1601DMBIT01011)

Client code

// A Java program for a Client


import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
public static void main(String args[])
{

try

{
Socket ss = new Socket("127.0.0.1",5502);

DataOutputStream out=new DataOutputStream(ss.getOutputStream());


DataInputStream in = new DataInputStream(ss.getInputStream());
Scanner sc = new Scanner(System.in);
System.out.println("Enter String");
String data = sc.nextLine(); out.writeUTF(data); String count = in.readUTF();

int n=Integer.parseInt(count); System.out.println("Length of String is : "+n); out.close();

ss.close();
}

catch(Exception e)
{
System.out.print("error"+e);
}
}
}

Server code

IT,SVIIT,Indore Page 5
Component Technology(BTIT-505) Suyash Jain(1601DMBIT01011)

// A Java program for a Server


import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(5502);
System.out.println("Wait for Establish a Connection.....");

Socket s=ss.accept();
//establishes connection
System.out.println("Establishes Connection between a Client and Server");

DataInputStream dis=new DataInputStream(s.getInputStream());


DataOutputStream out=new DataOutputStream(s.getOutputStream());

String str=(String)dis.readUTF();
System.out.println("Entered sting is "+str);
char [] ch = str.toCharArray();
int count=0;
for (int i = 0; i < ch.length; i++)
{
if (ch[i]!=' ');
{
count++;
}
}

String len = String.valueOf(count); out.writeUTF(len);


ss.close();

}
catch(Exception e)

{
System.out.println("Error"+e);
}
}
}

Output:

IT,SVIIT,Indore Page 6
Component Technology(BTIT-505) Suyash Jain(1601DMBIT01011)

Client :

Server:

IT,SVIIT,Indore Page 7

You might also like