Advanced Programming-NETWORK CH-04

You might also like

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

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

You might also like