Nothing Special   »   [go: up one dir, main page]

Socket Programming Theory - Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Socket Programming

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-

1. TCP (Transport Control Protocol) and


2. UDP (User Datagram Protocol)

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.

Hosts Identification and Service Ports

 Every computer on the Internet is identified by a unique, 4-byte IP address .


This is typically written in dotted quad format like 128.250.25.158 where each byte is an unsigned value
between 0 and 255. This representation is clearly not user-friendly because it is difficult to remember. Users use
the hostnames like www.google.com, which are easier to remember and Internet supports name servers (DNS)
that translate these names to IP addresses.

 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.

An internet Socket is identified by 6-byte integer.


Each Internet packet contains both the destination host address and the port
number on that host to which the message/request has to be delivered.

So, IP address can be thought of as a house address where a letter is sent


via post and Port number as the individual name to whom the letter has to
be delivered.

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.

TCP/UDP mapping of incoming packets to appropriate port/process

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 0 - 1024 are allocated to server services

 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.

Some common/well known port:

Port # Portocol Description


7 TCP, UDP ECHO protocol
20 TCP FTP - data port
21 TCP FTP – control/command port
23 TCP, UDP Telnet protocol - unencrypted text communications
25 TCP, UDP SMTP (Simple Mail Transport Protocol) - used for e-mail routing between
mailservers
37 TCP, UDP TIME protocol
42 TCP, UDP Host Name Server
53 TCP, UDP DNS (Domain Name System)
57 TCP MTP(Mail Transfer Protocol)
67 UDP BOOTP (BootStrap Protocol) server; also used by DHCP (Dynamic Host
Configuration Protocol)
68 UDP BOOTP client; also used by DHCP
69 UDP TFTP (Trivial File Transfer Protocol)
80 TCP HTTP (HyperText Transfer Protocol) - used for transferring web pages
101 TCP HOSTNAME
110 TCP POP3 (Post Office Protocol version 3) - used for retrieving E-mails
115 TCP SFTP, Simple File Transfer Protocol
161 TCP, UDP SNMP (Simple Network Management Protocol)
443 TCP HTTPS - HTTP Protocol over TLS/SSL (encrypted transmission)
513 TCP Login
513 UDP Who
546 TCP, UDP DHCPv6 client
547 TCP, UDP DHCPv6 server
Socket-based Communication
Sockets provide an interface for programming networks at the transport layer. Network communication using Sockets is
very much similar to performing file I/O. In fact, socket handle is treated like file handle.
The streams used in file I/O operation are also applicable to socket-based I/O. Socket-based communication is
independent of a programming language used for implementing it. That means, a socket program written in Java
language can communicate to a program written in non-Java (say C or C++) socket program.

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).

Three types of Internet sockets are supported:

Fig: Position of different Sockets


1. Stream sockets
 Connection Oriented- After the connection has been established, data can be read from and written to
these sockets as a byte stream.
 Allow processes to communicate using TCP
 Provide bidirectional, reliable, sequenced, and unduplicated flow of data
 Data is sent without errors or duplication and is received in the same order as it is sent.
 The socket type is SOCK_STREAM.

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.

4. Sequenced Packet Sockets


 Connection oriented
 Depends on SCTP
 Similar to a stream socket, with the exception that record boundaries are preserved.
 Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed
maximum length
 The socket type is SOCK_SEQPACKET.

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.

Client and server implementation

 TCP client/server implementation


 UDP client/server implementation

java.net package provides the following classes:

for Socket creation For Data exchange


Socket – for implementing a TCP client InputStream and OutputStream ( for TCP)
ServerSocket – for implementing a TCP server DatagramPacket ( for UDP)
DatagramSocket – for implementing both a UDP client and server
TCP client/server implementation UDP client/server implementation

Socket Programming and java.net package

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.

Some Classes for networking program-


ContentHandler InetAddress URL
DatagramPacket MulticastSocket URLConnection
DatagramSocket ServerSocket URLEncoder
DatagramSocketImpl Socket URLStreamHandler
HttpURLConnection SocketImpl

TCP Socket Programming


The two key classes from the java.net
package used in creation of server and client
programs are:
ServerSocket
Socket

A server program creates a specific type of


socket that is used to listen for client requests
(server socket).
In the case of a connection request, the program
creates a new socket through which it will
exchange data with the client using input and
output streams. The socket abstraction is very
similar to the file concept: developers have to
open a socket, perform I/O, and close it.
A simple Server Program in Java
The steps for creating a simple server program are:
1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes(“Hello\n”);
5. Close socket:
client.close();

A simple Client Program in Java


The steps for creating a simple client program are:
1. Create a Socket Object:
Socket client = new Socket(server address, PORT);
2. Create I/O streams for communicating with the server.
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);
4. Close the socket when done:
client.close();

Running Socket Programs

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 )

First, Run the class file for server program

C:\> java ServerProg

Then, Run the class file for Client program

C:\> java ClientProg

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 ");

String msg="Hello from Server"; //input text to be sent

//create output streams to write to the client socket


PrintWriter p=new PrintWriter(skt.getOutputStream(),true);
p.println(msg); // actual write or print to the client socket

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 ");

//Create input streams to read from the server


BufferedReader in=new BufferedReader(new InputStreamReader(skt.getInputStream()));
String msg=in.readLine(); //Read string from the server

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 ");

String msg="Hello from Server"; //input text to be sent

//create output streams to write to the client socket


PrintWriter p=new PrintWriter(skt.getOutputStream(),true);
p.println(msg); // actual write or print to the client socket

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 ");

//Create input streams to read from the server


BufferedReader in=new BufferedReader(new InputStreamReader(skt.getInputStream()));
String msg=in.readLine(); //Read string from the server

System.out.println("From Server:: " + msg); //prints the received text in display screen

skt.close();
}
catch(Exception e) {
System.out.println("Unsuccessful communication: " + e);
}
}
}

You might also like