Chapter Six
Network
Programming
By: Dahlak D. (MSc) 09/05/2025 1
1. Networking Basic
Network layer
• Applications Layer :- System apps (HTTP,FTP) and User apps
• Transport Layer :- TCP or UDP. programming interface: Socket
• Network Layer :- IP
• Link Layer :- Device driver
Network protocols
Transport Control Protocol (TCP) :- is a connection-oriented
protocol that provides a reliable flow of data between two computers.
User Datagram Protocol (UPD) :-is a protocol that sends
independent packets of data from one computer to another with no
guarantees about arrival.
By : Dahlak D. (MSc) 09/05/2025 2
2. Host and Port
The TCP and UDP protocols use ports to map incoming data to a
particular process running on a computer.
Port is represented by a positive (16-bit) integer value.
Destination in the Internet is identified by host + port.
Ports from 0 to 1024 are restricted Do not use them.
Some known ports are: 20, 21: FTP, 23: telnet, 25: SMTP, 80:
HTTP
By : Dahlak D. (MSc) 09/05/2025 3
3. Server / Client Model
Relationship between two computer programs
Server :- Receives communication and Provides services
• receives request for data, looks it up and delivers data
• E.g. Web Server or Database Server
Client :- Initiates communication and Requests services
• retrieves and display data or request and responds to user
input
• E.g. Web Browser or Chat Program
By : Dahlak D. (MSc) 09/05/2025 4
4. Client and Server Programming
Basic steps for client
1. Determine server location – IP address & port
2. Open network connection to server
3. Write data to server (request)
4. Read data from server (response)
5. Close network connection
6. Stop client
Basic steps for server
1. Determine server location - port (& IP address)
2. Create ServerSocket to listen for connections
3. While (true) {
4. accept network connection to client
5. Read data from client (request)
6. Write data to client (response)
7. Close network connection to client
8. }
By : Dahlak Daniel (MSc) 09/05/2025 5
5. Java Networking Packages
Java packages
• java.net ⇒ Networking
• java.io ⇒ I/O streams & utilities
• java.rmi ⇒ Remote Method Invocation
• java.security ⇒ Security policies
• java.lang ⇒ Threading classes
Java network classes
IP addresses :- InetAddress
Packets :- DatagramPacket
Sockets :- Socket, ServerSocket or DatagramSocket
URLs :- URL
By : Dahlak Daniel (MSc) 09/05/2025 6
5.1 InetAddress
It Represents an IP address
convert domain name to IP performs DNS lookup
Getting an InetAddress object
getLocalHost()
getByName(String host)
getByAddress(byte[] addr)
These methods return either a Inet4Address or a
Inet6Address
By : Dahlak Daniel (MSc) 09/05/2025 7
5.2 ServerSocket
Create socket on server
Constructor specifies local port and it listens to port
Usage
Begin waiting after invoking accept()
Listen for connection (from client socket)
Returns Socket for connection
Client uses constructor by providing:
IP address(machine name)
Port number
Transfer data via standard Java I/O streams
Methods
getInputStream()
getOutputStream()
close()
getInetAddress()
getPort()
getLocalPort()
By : Dahlak Daniel (MSc) 09/05/2025 8
6. Socket
Sockets provide an interface for programming networks at
the transport layer.
A server (program) runs on a specific computer and has a
socket that is bound to a specific port.
The server waits and listens to the socket for a client to
make a connection request.
A socket is an endpoint of a two-way communication
link between two programs running on the network.
A socket is bound to a port number so that the TCP layer
can identify the application that data destined to be sent.
Java’s .net package provides two classes:
ServerSocket – implements the server side of the
connection
Socket – implements the client side of the
connection
By : Dahlak Daniel (MSc) 09/05/2025 9
6.1 Socket Implementation on
Server
1. Open the Server Socket:
◦ ServerSocket server;
◦ DataOutputStream os;
◦ DataInputStream is;
◦ server = new ServerSocket( PORT );
2. Wait for the Client Request:
◦ Socket client = server.accept();
3. Create I/O streams for communicating to the client
◦ is = new DataInputStream( client.getInputStream() );
◦ 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 sockets:
◦ client.close();
By : Dahlak Daniel (MSc) 09/05/2025 10
6.2 Socket Implementation on
Client
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream() );
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();
By : Dahlak Daniel (MSc) 09/05/2025 11
6.3 Socket Exceptions
try
{
Socket client = new Socket(host, port);
handleConnection(client);
}
catch(UnknownHostException uhe)
{
System.out.println("Unknown host: " + host);
uhe.printStackTrace();
}
catch(IOException ioe)
{
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
By : Dahlak Daniel (MSc) 09/05/2025 12
6.4 ServerSocket Exceptions
public ServerSocket(intport) throws IOException
Creates a server socket on a specified port.
You can use getLocalPort() to identify the (assigned) port on which this
socket is listening.
The maximum queue length for incoming connection request is set to 50.
If a connection indication arrives when the queue is full, the connection is
refused.
Throws:
IOException - if an I/O error occurs when opening the socket.
SecurityException - if a security manager exists and its check Listen
method doesn't allow the operation.
By : Dahlak Daniel (MSc) 09/05/2025 13
7. Simple Server code
// SimpleServer.java: a simple server program
import java.net.*;
import java.io.*;
public class SimpleServer
{
public static void main(String args[]) throws IOException
{
ServerSocket s = new ServerSocket(1234); // Register service on port 1234
Socket s1=s.accept(); // Wait and accept a connection
OutputStream s1out = s1.getOutputStream(); // Get a comm stream for socket
DataOutputStream dos = new DataOutputStream (s1out);
dos.writeUTF("Hi there"); // Send a string!
dos.close(); // Close the connection, but not the server socket
s1out.close();
s1.close();
}
}
By : Dahlak Daniel (MSc) 09/05/2025 14
8. Client Code
// SimpleClient.java: a simple client program
import java.net.*;
import java.io.*;
public class SimpleClient
{
public static void main(String args[]) throws IOException
{
Socket s1 = new Socket(“localhost",1234); // Open connection to a server on port
1234
InputStream s1In = s1.getInputStream(); // file handle from the socket and read the
input
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());
System.out.println(st);
dis.close(); // When done, just close the connection and exit
s1In.close();
s1.close();
}
}
By : Dahlak Daniel (MSc) 09/05/2025 15
9. Socket functional calls
socket (): Create a socket
bind(): bind a socket to a local IP address and port #
listen(): passively waiting for connections
connect(): initiating connection to another socket
accept(): accept a new connection
Write(): write data to a socket
Read(): read data from a socket
sendto(): send a datagram to another UDP socket
recvfrom(): read a datagram from a UDP socket
close(): close a socket (tear down the connection)
Sockets
Client/server socket interaction:
TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
TCP create socket,
wait for incoming
connection requestconnection setup connect to hostid, port=x
connectionSocket = clientSocket =
welcomeSocket.accept() Socket()
send request using
read request from clientSocket
connectionSocket
write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
Client/server socket interaction:
UDP
Server (running on hostid) Client
create socket, create socket,
port=x, for clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket
read request from
serverSocket
write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port umber close
clientSocket
Thank
You !!!
Any Question ?
By: Dahlak D. (MSc) 09/05/2025 20