0% found this document useful (0 votes)
3 views19 pages

TCP and UDP Sockets Using Java.

The document outlines the implementation of TCP and UDP sockets using Java for a Computer Networks course. It explains the fundamental concepts of sockets, their types, and the client-server model, along with example code for both TCP and UDP communication. Additionally, it provides instructions for compiling and running the example programs.

Uploaded by

aashishjoshi559
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

TCP and UDP Sockets Using Java.

The document outlines the implementation of TCP and UDP sockets using Java for a Computer Networks course. It explains the fundamental concepts of sockets, their types, and the client-server model, along with example code for both TCP and UDP communication. Additionally, it provides instructions for compiling and running the example programs.

Uploaded by

aashishjoshi559
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSN303: Computer Networks

Session: 2025-26

B. Tech (CSE/IT) 5th Semester

Course Instructor

Dr Parul Saini
Experiment 7: Implement TCP sockets using Java.
Experiment 8: Implement UDP sockets using Java.
Overview
• A socket is an endpoint for communication between two computers
over a network.
• It allows a program (like a Java application, web browser, or email
client) to send and receive data through the network.
• Sockets in computer networks are used for allowing the transmission
of information between two processes of the same machines or
different machines in the network.
• Sockets work at the Transport Layer of the OSI model (Layer 4).They
use either:
• TCP (Transmission Control Protocol) - Reliable communication
• UDP (User Datagram Protocol) - Fast but unreliable communication

Prepared by Dr Parul Saini, DIT University 3


• Without sockets, programs couldn’t send data across networks.
Sockets allow:
• Communication between different computers (client ↔ server).
• Communication between different applications on the same computer.
• They’re the foundation of:
• Web browsing (HTTP over TCP)
• Email transfer (SMTP)
• File transfer (FTP)
• Chat applications
• Every socket connection involves:
• IP Address - Identifies the device on the network.
• Port Number - Identifies the specific application/service.
• Together, they form a socket address: Socket = IP Address + Port Number

Prepared by Dr Parul Saini, DIT University 4


• Example: [Link]:5000
• means communication with the device having IP [Link] using port
5000.
• A port is a logical number that helps a computer distinguish between
different types of network services or applications running on it.
• There are 65,535 ports available (because port numbers are 16-bit
values). They are grouped into categories:
Port Range Type Usage
Reserved for common system
0 – 1023 Well-known ports
services (HTTP, FTP, DNS, etc.)
Used by user applications (e.g.,
1024 – 49151 Registered ports
database servers, games)
Used temporarily by client
49152 – 65535 Dynamic/Private ports programs (also called ephemeral
ports)

Prepared by Dr Parul Saini, DIT University 5


Service Description Port Number
HTTP Web Server Used for websites 80
HTTPS (Secure Web) Encrypted web traffic 443
FTP File Transfer Protocol 21
SSH Secure login 22
SMTP Sending emails 25
DNS Domain Name Resolution 53

Types of Sockets
Type Protocol Description Example
Reliable, connection-
Stream Socket TCP Web server, Email, Chat
oriented
Online games, VoIP, Video
Datagram Socket UDP Fast, connectionless
streaming

Prepared by Dr Parul Saini, DIT University 6


• Socket communication follows a Client–Server model.

Step Server Side Client Side

1 Creates a ServerSocket and waits for connection. Creates a Socket to connect to the server.

2 Accepts the connection when a client requests. Connects to the server’s IP and port.

3 Data is exchanged via input/output streams. Data is exchanged via input/output streams.

4 Both sides close the connection when done. Connection is closed.

Prepared by Dr Parul Saini, DIT University 7


Common TCP Socket Functions and Their
Description
Function Call Description
create() Creates a new socket (an endpoint for communication).
Assigns an address (IP + port number) to the socket so others can
bind()
contact it.
Server puts the socket in listening mode, waiting for connection
listen()
requests from clients.
accept() The server accepts an incoming connection request from a client.
connect() The client tries to connect to the server socket.
write() / send() Sends data through the socket to the other side.

read() / recv() Receives data from the socket.

close() Closes the connection and frees resources.


Prepared by Dr Parul Saini, DIT University 8
TCP sockets using Java
• Transmission Control Protocol (TCP) is a reliable connection-oriented
protocol of the transport layer.
TCP socket at the client-side: TCP socket at the server-side:

• The first step is to create a socket and use • Use socket() for establishing a socket.
the socket() function to create a socket. • Use the bind() function for binding the
• Use the connect() function for connecting socket to an address.
the socket to the server address. • Then for listening client connections use
• Transmit data between two communicating listen() function.
parties using read() and write() functions. • The accept() function is used for accepting
• After data transmission completion close the the connection of the client.
connection using close() function. • Transmit data with the help of the read() and
write() function.
Prepared by Dr Parul Saini, DIT University 9
Prepared by Dr Parul Saini, DIT University 10
Example: Java TCP Socket Communication
• [Link] • [Link]
import [Link].*; import [Link].*;
import [Link].*; import [Link].*;
public class SimpleServer { public class SimpleClient {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(5000); Socket socket = new Socket("localhost", 5000);
[Link]("Server is waiting for client..."); BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
Socket socket = [Link](); PrintWriter out = new PrintWriter([Link](), true);
[Link]("Client connected!"); [Link]("Hi Server! This is the Client.");
BufferedReader in = new BufferedReader(new InputStreamReader([Link]())); String reply = [Link]();
PrintWriter out = new PrintWriter([Link](), true); [Link]("Server replied: " + reply);
String message = [Link](); [Link]();
[Link]("Client says: " + message); }
[Link]("Hello Client, message received!"); }
[Link]();
[Link]();
}
}
Prepared by Dr Parul Saini, DIT University 11
• Open Command Prompt
• Navigate to the folder where you saved both files.
• Run the following commands:
• javac [Link]
• javac [Link]
• This will generate two .class files: [Link] and [Link]
• Run the server program: java SimpleServer
• Output: Server is waiting for client...
• The server is now listening on port 5000 for incoming connections. Keep this
window open.
• Now, open another Command Prompt window (or a new terminal tab).Run
the client program: java SimpleClient
• Output on the Client side: Server replied: Hello Client, message received!
• Output on the Server side: Server is waiting for client...
Client connected!
Client says: Hi Server! This is the Client.
Prepared by Dr Parul Saini, DIT University 12
UDP sockets using Java
• User Datagram Protocol (UDP) is a connection-less and unreliable
protocol of transport layer.
UDP socket at the client-side: UDP socket at the server-side:

• Use socket() function for creating socket; • Create a socket using the socket() function.
• recvfrom() and sendto() functions are used • Use the bind() function for the binding
for transmitting data between two socket to an address.
communicating parties. • Transmit data with the help of the recvfrom()
function and sendto().

Prepared by Dr Parul Saini, DIT University 13


UDP Socket Classes in Java

Class Description
DatagramSocket Used to send or receive UDP packets.
DatagramPacket Represents the actual packet (data + address + port).
InetAddress Used to specify the receiver's IP address.

Prepared by Dr Parul Saini, DIT University 14


Prepared by Dr Parul Saini, DIT University 15
Example: Java UDP Socket Communication
• [Link] // Prepare reply
import [Link].*; String serverMsg = "Message received: " + clientMsg;
public class UDPServer { sendData = [Link]();
public static void main(String[] args) { InetAddress clientIP = [Link]();
try { int clientPort = [Link]();
DatagramSocket serverSocket = new DatagramSocket(9876); // Port number // Send reply back to client
byte[] receiveData = new byte[1024]; DatagramPacket sendPacket = new DatagramPacket(sendData, [Link], clientIP,
byte[] sendData; clientPort);

[Link]("UDP Server is running and waiting for client..."); [Link](sendPacket);

while (true) { }

// Receive packet [Link]();

DatagramPacket receivePacket = new DatagramPacket(receiveData, [Link]); } catch (Exception e) {

[Link](receivePacket); [Link]();

String clientMsg = new String([Link](), 0, [Link]()); }

[Link]("Client says: " + clientMsg); }

if ([Link]("exit")) { }

[Link]("Client ended the chat."); }

break;
} Prepared by Dr Parul Saini, DIT University 16
Example: Java UDP Socket Communication
• [Link] // Send packet to server
import [Link].*; DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
IPAddress, 9876);
import [Link].*;
[Link](sendPacket);
public class UDPClient {
if ([Link]("exit")) {
public static void main(String[] args) {
[Link]("Chat ended by client.");
try {
break;
DatagramSocket clientSocket = new DatagramSocket();
}
InetAddress IPAddress = [Link]("localhost");
// Receive reply from server
BufferedReader userInput = new BufferedReader(new InputStreamReader([Link]));
DatagramPacket receivePacket = new DatagramPacket(receiveData, [Link]);
byte[] sendData;
[Link](receivePacket);
byte[] receiveData = new byte[1024];
modifiedSentence = new String([Link](), 0, [Link]());
String sentence, modifiedSentence;
[Link]("Server: " + modifiedSentence);
[Link]("Connected to UDP Server. Type 'exit' to quit.");
}
while (true) {
[Link]();
[Link]("Client: ");
} catch (Exception e) {
sentence = [Link]();
[Link]();
sendData = [Link]();
}
}
}
Prepared by Dr Parul Saini, DIT University 17
• Open Command Prompt
• Navigate to the folder where you saved both files.
• Run the following commands:
• javac [Link]
• javac [Link]
• Run the server program: java UDPServer
• Output: UDP Server is running and waiting for client...
• Now, open another Command Prompt window (or a new terminal
tab).Run the client program: java UDPClient
• Output on the Client side: Connected to UDP Server. Type 'exit' to quit.
Client: Hello Server!
Server: Message received: Hello Server!
• Output on the Server side: UDP Server is running and waiting for client...
Client says: Hello Server!

Prepared by Dr Parul Saini, DIT University 18


References
• Tanenbaum, A. S., & Wetherall, D. J. (2011). Computer Networks (5th
ed.). Pearson.
• [Link]
programming/

Prepared by Dr Parul Saini, DIT University 19

You might also like