Socket Programming Theory - Final
Socket Programming Theory - Final
Socket Programming Theory - Final
Internet and WWW have emerged as global ubiquitous media for communication and changed the way we conduct
science, engineering, and commerce. They are also changing the way we learn, live, enjoy, communicate, interact,
engage, etc. The modern life activities are getting completely centered around or driven by the Internet. To take
advantage of opportunities presented by the Internet, businesses are continuously seeking new and innovative ways and
means for offering their services via the Internet. This created a huge demand for software designers and engineers with
skills in creating new Internet-enabled applications or porting existing/legacy applications to the Internet platform.
Client/Server Communication
At a basic level, network-based systems consist of a server, client, and a media for communication as shown in Fig.
Below.
A computer running a program that makes a request for services is called client machine.
A computer running a program that offers requested services from one or more clients is called server
machine.
The media for communication can be wired or wireless network through which request and response
propagate.
Generally, programs running on client machines make requests to a program (often called as server program) running on
a server machine.
To use the communication channel, an application program both at server end as well as client end needs to
request the underlying OS to create a software abstract/interface. This is known as a socket which simulates a
hardware socket.
“A socket is an abstraction through which an application may send and receive data, in much the same way as
an open file handle allows an application to read and write data to stable storage”
A socket is an interface between an application program and transport layer of the protocol stack.
They involve networking services provided by the transport layer, which is part of the Internet software stack,
often called TCP/IP (Transport Control Protocol/Internet Protocol) stack, shown in Fig above.
The transport layer comprises two types of protocols-
The most widely used programming interfaces for these protocols are sockets.
TCP is a connection-oriented protocol that provides a reliable flow of data between two computers. Example
applications that use such services are HTTP, FTP, and Telnet.
UDP is a protocol that sends independent packets of data, called datagrams, from one computer to another with
no guarantees about arrival and sequencing. Example applications that use such services include Clock server
and Ping.
In general, each computer only has one Internet address. However, computers often need to communicate more
than one type of service or to talk to multiple hosts/computers at a time.
For example- ftp sessions, web connections, and chat programs which are running at the same time.
To distinguish these services, each service offered by a computer is uniquely identified by a port number (a
logical access point) represented by a 2-byte integer number.
It should be clear by now that the IP addresses and port numbers play different roles in selecting the final destination of
data. The destination IP address defines the host among the different hosts in the world. After the host has been selected,
the port number defines one of the processes on this particular host.
The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.
The ports are used by TCP and UDP protocols to identify the destination process (application) of an incoming data.
Port Numbers:
A port number/port address is transport layer address which identifies a specific process or service in a client
server system.
In the Internet model, Port is represented by a positive (16-bit) integer value between 0 and 65,535.
The Internet has decided to use universal port numbers for servers; these are called well-known port numbers.
Port numbers 1024 - 65535 are available for the following user level applications/process:
o Port numbers 1024 - 49151 are reserved for user server applications.
o Port numbers 49152 - 65535 are reserved for clients.
IANA Ranges
The IANA (Internet Assigned Number Authority) has divided the port numbers into three ranges: -
Well-known ports
- ranging from 0 to 1023
- are assigned and controlled by IANA.
- All well-known protocols are assigned with different well-known port numbers.
Registered ports-
- ranging from 1024 to 49,151
- are not assigned or controlled by IANA.
- can only be registered with IANA to prevent duplication.
- User level process or services use these port numbers.
Dynamic or Private ports-
- ranging from 49,152 to 65,535
- are neither controlled nor registered.
- can be used by any process. These are the ephemeral ports.
- Used for temporary purpose for private usage.
Server
passively waits for and responds to clients
passive socket
Client
initiates the communication
must know the address and the port of the server
active socket
Procedure:
A server (program) runs on a specific computer and has a socket that is bound to a specific port.
The server listens to the socket and waits for a client to make a connection request (see Fig. a).
If everything goes well, the server accepts the incoming connection (see Fig. b).
Upon acceptance, the server gets a new socket bound to a different port. It needs a new socket
(consequently a different port number) so that it can continue to listen to the original socket for
connection requests while serving the connected client.
Types of Sockets:
Internet Sockets, unix sockets, X.25 sockets etc .
Internet sockets characterized by IP Address (4 bytes) and port number (2 bytes).
2. Datagram sockets
Allow processes to use UDP to communicate.
Supports bidirectional flow of messages.
Less reliable- A process on a datagram socket can receive messages in a different order from the sending
sequence and can receive duplicate messages.
The socket type is SOCK_DGRAM.
3. Raw sockets
Provide access to ICMP.
Are normally datagram oriented, although their exact characteristics are dependent on the interface provided
by the protocol.
Allows direct access to lower-layer protocols such as Internet Protocol (IP)
The socket type is SOCK_RAW.
Function flow for Connection oriented service Function flow for Connection oriented service
(TCP Protocol) (UDP Protocol)
** [ for C Library ]
Listen(), connect(), accept() adds the reliability to the service
The steps involved in establishing a socket on the client side are as follows:
1. Create a socket with the socket() system call
2. Connect the socket to the address of the server using the connect() system call
3. Send and receive data using the read() and write()system calls
The steps involved in establishing a socket on the server side are as follows:
1. Create a socket with the socket() system call
2. Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address
consists of a port number on the host machine.
3. Listen for connections with the listen() system call
4. Accept a connection with the accept() system call. This call typically blocks until a client connects with the
server.
5. Send and receive data using the read() and write()system calls
Socket() - creates an endpoint for communication and returns a socket descriptor representing the endpoint. It
returns -1 on error. In JAVA, it generates exception.
Bind()- binds the socket with a port number in local machine
Listen()- the server waits for incoming connections sent from the client
Accept() - gets the pending connection on the port where the server are listening on.
Connect()- Connect the client to the server address. At this point, the connection is established between client and
server, and they are ready to transfer data.
write() ,read() / send(), recv() / sendto(), recvfrom()– used for data exchange over the connection
Close()- closes the connection corresponding to the socket and frees up the port used by the socket. It returns 0 if
successful, returns -1 if error.
This section introduces elements of network programming and concepts involved in creating network applications using
sockets. To enable the rapid development of network applications, Java provides a set of classes (defined in a package
called java.net) required for creating sockets and message communication using two different protocols.
A socket is an endpoint of a two-way communication link between two programs running on the network.
Socket is bound to a port number so that the TCP layer can identify the application that data is destined to be
sent.
Open two command prompt (for windows) or open two terminal window (for UNIX)
Compile both server and client programs in different command prompt window
( server program and client program may run on same machine or different machine )
The server programs runs at first, because server listens to the socket and waits for a client to make a connection
request. After that Client program runs. If everything goes well, the server accepts the incoming connection and next
data exchange is performed.
It should be noted that once the server program execution is started, it is not possible for any other server program to
run on the same port until the first program which is successful using it is terminated. Port numbers are a mutually
exclusive resource. They cannot be shared among different processes at the same time.
Socket Program 1: //Server send, Client Receive (Fixed String)
Using TCP/IP socket, write a client-server program in java where server sends a text to client and after receiving the
client prints the text. (Implement in Local Machine) . using a throws keyword to handle the exception
FileName- ServerSendString.java
import java.io.*;
import java.net.*;
public class ServerSendString
{
public static void main(String [] s) throws Exception
{
ServerSocket srvr=new ServerSocket(1234); //opens the connection channel
Socket skt=srvr.accept(); //responds to the connection
System.out.println("Server Connected ");
skt.close();
srvr.close();
}
}
FileName- ClientRcvString.java
import java.io.*;
import java.net.*;
public class ClientRcvString
{
public static void main(String [] s) throws Exception
{
Socket skt=new Socket("localhost",1234); // Connect to the server
System.out.println("Client Connected ");
System.out.println("From Server:: " + msg); //prints the received text in display screen
skt.close();
}
}
Socket Program 1: //Server send, Client Receive (Fixed String)
Using TCP/IP socket, write a client-server program in java where server sends a text to client and after receiving the
client prints the text. (Implement in Local Machine) . using a try-catch statement to handle the exception
FileName- ServerSendString.java
import java.io.*;
import java.net.*;
public class ServerSendString
{
public static void main(String [] s)
{
try{
ServerSocket srvr=new ServerSocket(1234); //opens the connection channel
Socket skt=srvr.accept(); //responds to the connection
System.out.println("Server Connected ");
skt.close();
srvr.close();
}
catch(Exception e) {
System.out.println("Unsuccessful communication: " + e);
}
}
}
FileName- ClientRcvString.java
import java.io.*;
import java.net.*;
public class ClientRcvString
{
public static void main(String [] s)
{
try{
Socket skt=new Socket("localhost",1234); // Connect to the server
System.out.println("Client Connected ");
System.out.println("From Server:: " + msg); //prints the received text in display screen
skt.close();
}
catch(Exception e) {
System.out.println("Unsuccessful communication: " + e);
}
}
}