CHAPTER 04: Network Programming
By: Muleta Taye T. E-mail: muleta.taye@aastu.edu.et
May 3, 2023
CH03: Topics to be covered
4.1 Overview of Sockets
4.2 Establishing Connections
4.3 TCP Clients and Servers
4.4 UDP Clients and Servers
4.5 Secure Sockets Layer
By: Mule Ta – 2
CH04: Network Programming
What is Network ?
By: Mule Ta – 3
CH04: Network Programming
What is Network ?
an Interconnection between computing machine.
Modern-day applications 7→ Internet based or Web-Based!
↓ java handles via
• Network Programming!
java.net package provides
stream-based communications: Enable applications to view networking as
streams of data
packet-based communications: for transmitting individual packets of information
Java provides two mechanisms for distributed computing
Socket-based communication
• Enable applications to view networking as if it were file I/O
↓ achieved via
By: Mule Ta – 3
CH04: Network Programming
What is Network ?
an Interconnection between computing machine.
Modern-day applications 7→ Internet based or Web-Based!
↓ java handles via
• Network Programming!
java.net package provides
stream-based communications: Enable applications to view networking as
streams of data
packet-based communications: for transmitting individual packets of information
Java provides two mechanisms for distributed computing
Socket-based communication
• Enable applications to view networking as if it were file I/O
↓ achieved via
Socket Programming!
By: Mule Ta – 3
CH04: Network Programming
What is Network ?
an Interconnection between computing machine.
Modern-day applications 7→ Internet based or Web-Based!
↓ java handles via
• Network Programming!
java.net package provides
stream-based communications: Enable applications to view networking as
streams of data
packet-based communications: for transmitting individual packets of information
Java provides two mechanisms for distributed computing
Socket-based communication
• Enable applications to view networking as if it were file I/O
↓ achieved via
Socket Programming!
Remote method invocation (RMI)
• N’Z scope of the chapter ....
By: Mule Ta – 3
CH04: Network Programming
What are Sockets ?
are a communication endpoint that serves as a link between two machines
on a network.
defined by:
IP address : to uniquely identify devices
Port Number : TCP/IP layer can use to identify the application that receives the
data
There are two kinds of sockets:
Client socket 7→ can be used to send and receive data.
Server socket 7→ waits for requests from clients
So Socket programming,
is a means of communicating data between two computers across a network.
Connection required! 7→ How ?
By: Mule Ta – 4
CH04: Network Programming
What are Sockets ?
are a communication endpoint that serves as a link between two machines
on a network.
defined by:
IP address : to uniquely identify devices
Port Number : TCP/IP layer can use to identify the application that receives the
data
There are two kinds of sockets:
Client socket 7→ can be used to send and receive data.
Server socket 7→ waits for requests from clients
So Socket programming,
is a means of communicating data between two computers across a network.
Connection required! 7→ How ?
• connection-oriented protocol 7→ TCP
• connectionless protocol 7→ UDP.
Port number is necessary to distinguish different server applications running on
the same host
By: Mule Ta – 4
CH04: Network Programming
Java provides provides Collection of classes and interfaces.
↓ contained
java.net package
impport java.net.*;
// input and output streams to write to and read from while communicating
import java.io.*;
java.net has two classes :
Socket:
java.net.Socket 7→ represents a socket
ServerSocket:
java.net.ServerSocket
↘
provides a mechanism for the server program to listen for clients and establish
connections with them
How TCP connection between two computers using sockets ?
↓
following steps occur when establishing
By: Mule Ta – 5
CH04: Network Programming
Steps in establishing connection:
1. The server instantiates a ServerSocket object.
denoting which port number communication is to occur on.
By: Mule Ta – 6
CH04: Network Programming
Steps in establishing connection:
1. The server instantiates a ServerSocket object.
denoting which port number communication is to occur on.
2. The server invokes the accept method of the ServerSocket class
This method waits until a client connects to the server on the given port.
By: Mule Ta – 6
CH04: Network Programming
Steps in establishing connection:
1. The server instantiates a ServerSocket object.
denoting which port number communication is to occur on.
2. The server invokes the accept method of the ServerSocket class
This method waits until a client connects to the server on the given port.
3. A client instantiates a Socket object
Specifying the server name and port number to connect to.
By: Mule Ta – 6
CH04: Network Programming
Steps in establishing connection:
1. The server instantiates a ServerSocket object.
denoting which port number communication is to occur on.
2. The server invokes the accept method of the ServerSocket class
This method waits until a client connects to the server on the given port.
3. A client instantiates a Socket object
Specifying the server name and port number to connect to.
4. The constructor of the Socket class attempts to connect the client to the
specified server and port number
By: Mule Ta – 6
CH04: Network Programming
Steps in establishing connection:
1. The server instantiates a ServerSocket object.
denoting which port number communication is to occur on.
2. The server invokes the accept method of the ServerSocket class
This method waits until a client connects to the server on the given port.
3. A client instantiates a Socket object
Specifying the server name and port number to connect to.
4. The constructor of the Socket class attempts to connect the client to the
specified server and port number
5. On the server side, the accept method returns a reference to a new socket
on the server that is connected to the client’s socket
↓
if (connection is successful)
communication can occur using I/O streams
socket has both an OutputStream and an InputStream
The client’s OutputStream 7→ connected to the server’s InputStream.
The client’s InputStream 7→ connected to the server’s OutputStream
By: Mule Ta – 6
CH04: Network Programming
Figure 1: Socket API
By: Mule Ta – 7
CH04: Network Programming
CLIENT SIDE SERVER SIDE
import java.io.*;
import java.io.*;
import java.net.*;
import java.net.*;
public class ServerSideCommunication {
public class ClientSideCommunication {
public ClientSideCommunication(String address, int port)
private Socket socket = null;
// client connection
try{
// starts server and waits for a connection
// Client socket
try{
Socket socket = new Socket(address, port);
ServerSocket server = new ServerSocket(port);
// takes input from terminal
System.out.println("Server Service started");
DataInputStream input = new DataInputStream(System.in);
System.out.println("Waiting for a client ...");
socket = server.accept();
// sends output to the socket
System.out.println("Client accepted");
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
// takes input from the client socket
}
DataInputStream recv = new DataInputStream(
catch (UnknownHostException u) {
new BufferedInputStream(socket.getInputStream()));
System.out.println(u);
return;
String readFromClent = "";
}
while (!readFromClent.equals("eol")) {
String addressandIp = "";
try {
while (!addressandIp.equals("eol")) {
readFromClent = recv.readUTF();
try {
addressandIp = input.readLine();
}
out.writeUTF(addressandIp);
catch(IOException exception) {
}
System.out.println(exception);
catch(IOException exception) {
}
System.out.println(exception);
}
}
}
By: Mule Ta – 8
CH04: Network Programming
// close the connection
System.out.println("Closing connection");
try {
// close connection
input.close();
socket.close();
out.close();
recv.close();
socket.close();
}
}
catch(IOException ex)
catch (IOException ex) {
{
System.out.println(ex);
System.out.println(ex);
}
}
}
}
public static void main(String args[]) {
public static void main(String args[]) {
ServerSideCommunication server =
ClientSideCommunication client =
new ServerSideCommunication(6060);
new ClientSideCommunication("192.168.12.2", 6060);
}
}
}
}
By: Mule Ta – 9
CH04: Network Programming
The ServerSocket class can be used to create a server socket
has constructor:
No Methods Description
1 public ServerSocket(int port) throws IOException Attempts to create a server socket bound to the
specified port. An exception occurs if the port is
already bound by another application.
2 public ServerSocket(int port, int backlog) throws IOException the backlog parameter specifies how many incoming
clients to store in a wait queue
3 public ServerSocket(int port, int backlog, InetAddress InetAddress parameter specifies the local IP address
address) throws IOException to bind to.
4 public ServerSocket throws IOException Creates an unbound server socket. When using this
constructor, use the bind method when you are ready
to bind the server socket
By: Mule Ta – 10
CH04: Network Programming
The ServerSocket class can be used to create a server socket
has constructor:
No Methods Description
1 public ServerSocket(int port) throws IOException Attempts to create a server socket bound to the
specified port. An exception occurs if the port is
already bound by another application.
2 public ServerSocket(int port, int backlog) throws IOException the backlog parameter specifies how many incoming
clients to store in a wait queue
3 public ServerSocket(int port, int backlog, InetAddress InetAddress parameter specifies the local IP address
address) throws IOException to bind to.
4 public ServerSocket throws IOException Creates an unbound server socket. When using this
constructor, use the bind method when you are ready
to bind the server socket
has Methods
public int getLocalPort()
Returns the port that the server socket is listening on.
public Socket accept() throws IOException
Waits for an incoming client
blocks until either a client connects to the server on the specified port or the
socket times out
By: Mule Ta – 10
CH04: Network Programming
Has Methods ...
public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during
the accept.
public void bind(Socket Addresshost, int backlog)
Binds the socket to the specified server and port in the SocketAddress object.
▶ Java InetAddress class
represents an IP address
provides methods to get the IP of any host name
1. static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .
2. static InetAddress getByName(String host)
Determines the IP address of a host, given the host’s name.
3. String getHostAddress()
Returns the IP address string in textual presentation.
4. String getHostName()
Gets the host name for this IP address.
By: Mule Ta – 11
CH04: Network Programming
import java.io.*;
import java.io.*; import java.net.*;
import java.net.*; public class IntAddressTestDemo{
public class IntAddressTestDemo{ public static void main(String [] agrs){
public static void main(String [] agrs){ byte address[]={142,250,201,142};
try{ try{
InetAddress ip=InetAddress.getByName("www.aastu.edu.et"); InetAddress ip=InetAddress.getByAddress(address);
System.out.println("Host Name: "+ip.getHostName()); System.out.println("IP Address: "+ip.getHostAddress());
System.out.println("IP Address: "+ip.getHostAddress()); System.out.println("Host Name: "+ip.getHostName());
}
catch(Exception e){ }
System.out.println(e); catch(Exception e){
} System.out.println(e);
} }
} }
Output: }
Host Name: www.aastu.edu.et Output:
IP Address: 197.156.73.161 IP Address: 142.250.201.142
Host Name: www.google.com
By: Mule Ta – 12
CH04: Network Programming
What is UDP ?
stands for User datagram protocol.
Connectionless Transport layer protocol
primarily used to establish low-latency and loss-tolerating connections between
applications on the internet.
beneficial in time-sensitive communications.
VoIP, DNS, multimedia data
How Java Implements UDP then?
Two main classes
• DatagramPacket : is a data container
• DatagramSocket : is a mechanism to send and receive DatagramPackets.
↓
data transferred is encapsulated in a unit 7→ DATAGRAM
↙
independent, self-contained message sent over the network whose
arrival, arrival time, and content are not guaranteed
By: Mule Ta – 13
CH04: Network Programming
DatagramPacket object is created using :
DatagramPacket(byte[ ] buf, int length)
the data must be in the form of an array of bytes
is used to create a DatagramPacket to be received.
DatagramPacket(byte[ ] data, int length, InetAddress address, int port)
creates a DatagramPacket to be sent.
the address and port number of the destination host
DatagramSocket
is used to send and receive DatagramPackets.
DatagramSocket represents a UDP connection between two Parties in a
network.
is a class for both client and the server.
to establish, send and receive:
DatagramSocket(): used to create a client that binds to an arbitrary port
number.
DatagramSocket(int port)
• is used to create a server that binds to the specific port number, so the clients
know how to connect to.
DatagramSocket(int port, InetAddress addr, int port)
• the third constructor binds the server to the specified IP address
By: Mule Ta – 14
CH04: Network Programming
Any Methods ?
send(DatagramPacket p): sends a datagram packet.
receive(DatagramPacket p): receives a datagram packet.
setSoTimeout(int timeout):
↓
sets timeout in milliseconds, limiting the waiting time when receiving data.
↓
• If the timeout expires, a SocketTimeoutException is raised.
close(): closes the socket.
Exceptions raised:
IOException, PortUnreachableException, SocketTimeoutException
By: Mule Ta – 15
CH04: Network Programming
DatagramPacket has six methods: 7→ The get Families
No Methods Description
1 public InetAddress getAddress( ) returns an InetAddress object containing the address
of the remote host
2 public int getPort() returns an integer specifying the remote port.
3 public byte[ ] getData() returns a byte array containing the data from the
datagram
4 public int getLength() returns the number of bytes of data in the datagram
DatagramPacket has methods: 7→ The set Families 7→ Why?
↙
”for changing the data, remote address, and remote port after the
datagram has been created.”
No Methods Description
1 public InetAddress getAddress( ) changes the payload of the UDP datagram
2 public void setData(byte[] data, int offset, int length) provides an alternative approach to sending a large
quantity of data..
3 public void setAddress(InetAddress remote) changes the address a datagram packet is sent to
4 public void setAddress(SocketAddress remote) rchanges the address and port a datagram packet is
By: Mule Ta – sent to 16
CH04: Network Programming
UDP CLIENT SIDE
import java.io.*; UDPSERVER SIDE
import java.net.*;
public class UDPClientSide { import java.io.*;
//server port which we connect to import java.net.*;
public final static int SERVICE_PORT = 4500; public class UDPServerSide {
public static void main(String args []) { public final static int SERVICE_PORT = 4500;
try { public static void main(String args []) {
try {
// Instantiate client socket //Instantiate a new DatagramSocket to receive responses
DatagramSocket clientSocket = new DatagramSocket(); DatagramSocket serverSocket = new DatagramSocket(
// what is z IP Address of the server SERVICE_PORT
InetAddress IPAddress = InetAddress.getByName("localhost"); );
// creating buffer for storing datagram // creating temporary location
byte[] receivingDataBuffer = new byte[512];
byte[] sendingDataBuffer = new byte[512]; byte[] sendingDataBuffer = new byte[512];
byte[] receivingDataBuffer = new byte[512];
DatagramPacket inputPacket = new DatagramPacket(
String dataFromClient = "Sending data from the client"; receivingDataBuffer,
sendingDataBuffer = dataFromClient.getBytes(); receivingDataBuffer.length);
System.out.println("Waiting for a client to connect...");
// Creating a UDP packet
DatagramPacket sendingPacket = new DatagramPacket( Receive data from the client and store in inputPacket
sendingDataBuffer, serverSocket.receive(inputPacket);
sendingDataBuffer.length,
IPAddress, // perform an action based on the request
SERVICE_PORT
); // Obtain client’s IP address and the port
InetAddress senderAddress = inputPacket.getAddress();
// sending UDP packet to the server int senderPort = inputPacket.getPort();
clientSocket.send(sendingPacket);
By: Mule Ta – 17
CH04: Network Programming
// Get the server response .i.e. capitalized sentence
DatagramPacket receivingPacket = new DatagramPacket(
receivingDataBuffer,
// Create new UDP packet with data to send to the client
receivingDataBuffer.length
DatagramPacket outputPacket = new DatagramPacket(
);
sendingDataBuffer,
sendingDataBuffer.length,
clientSocket.receive(receivingPacket);
senderAddress,senderPort
);
// Printing the received data
// Send the created packet to client
String receivedData = new String(receivingPacket.getData());
serverSocket.send(outputPacket);
System.out.println("Sent from the server: "+receivedData);
// Close the socket connection
serverSocket.close();
// Closing the socket connection with the server
}
clientSocket.close();
catch (SocketException e){
}
e.printStackTrace();
catch(SocketException e) {
}
e.printStackTrace();
}
}
}
}
}
By: Mule Ta – 18
CH04: Network Programming
Confidential communication through an open channel requires Security.
Secured Socket Layer (SSL) enables a secured connection between two parties.
↙
How ?
↘
By providing a secure channel between two devices operating over a network
connection
SSL support the ff security principles
Authentication 7→ ensure the server we connect to is indeed the proper
server
Encryption 7→ protect data transmissions between parties
Data integrity 7→ guarantee that the requested data is what is effectively
delivered
By: Mule Ta – 19
CH04: Network Programming
Java provides 3 API’s for secured communication.
Java Secured-Socket Extension (JSSE)
Java Cryptography Architecture (JCA)
Java Cryptographic Extension (JCE)
↓
By: Mule Ta – 20
CH04: Network Programming
Java provides 3 API’s for secured communication.
Java Secured-Socket Extension (JSSE)
Java Cryptography Architecture (JCA)
Java Cryptographic Extension (JCE)
↓
First Assignment ....
Review and internalize all the API’s
Try to Answer when to use and How to use
Write a simple snippet for secure Payment transaction system.
By: Mule Ta – 20
Done!
Question!
By: Mule Ta – 21