INSTITUT D’ENSEIGNEMENT SUPÉRIEUR DE RUHENGERI
B.P. 155, Ruhengeri, Rwanda
T : +250 788 90 30 30, +250 788 90 30 32,W : www.ines.ac.rw, E :
[email protected] FACULTY OF SCIENCES AND INFORMATON
TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE
Advanced Java Programming
- Networking in Java -
by:
Clement Munyentwari
NETWORKING IN JAVA
● Networking refers to the exchange of data between
computers over a shared medium (e.g., LAN, WAN,
Internet).
● Java Networking API:
○ Java provides the java.net package for networking
applications. It supports both TCP and UDP
protocols.
● Importance in Java:
○ Java's platform independence makes it ideal for
network programming, which is essential for building
distributed systems, web applications, and more.
BASIC CONCEPTS
● IP Address: A unique identifier for a device on a
network.
● Port: A virtual point where network connections
start and end.
● Protocol: Rules for data transmission (e.g., TCP,
UDP).
● Socket: An endpoint for communication between
two machines.
TCP VS UDP
● TCP (Transmission Control Protocol):
○ Reliable, connection-oriented protocol.
○ Ensures data is received in the correct order.
○ Example Use: File transfer, HTTP.
● UDP (User Datagram Protocol):
○ Unreliable, connectionless protocol.
○ Faster but does not guarantee delivery or order.
○ Example Use: Live streaming, online gaming.
CLASSES
● InetAddress: Represents an IP address.
○ Methods: getByName(), getLocalHost(),
getHostAddress().
● Socket: Represents a TCP connection.
○ Constructor: Socket(String host, int port).
● ServerSocket: Listens for incoming TCP connections.
○ Constructor: ServerSocket(int port).
● DatagramSocket: Represents a UDP connection.
○ Methods: send(), receive().
● DatagramPacket: Represents a packet of data for UDP.
○ Constructor: DatagramPacket(byte[] buf, int length).
ESTABLISHING TCP
● Client-Server Model:
○ Client: Initiates the connection.
○ Server: Listens for connections.
● Steps:
○ Server creates a ServerSocket.
○ Client creates a Socket to connect to the server.
○ Server accepts the connection using accept()
method.
○ Communication occurs via InputStream and
OutputStream.
EXAMPLE: TCP CLIENT-SERVER
● Server code: BufferedReader reader = new
import java.io.*; BufferedReader(new
import java.net.*; InputStreamReader(input));
public class SimpleServer { String message =
public static void main(String[] reader.readLine();
args) { System.out.println("Received: " +
try (ServerSocket serverSocket = message);
new ServerSocket(5000)) { } catch (IOException ex) {
System.out.println("Server is ex.printStackTrace();
listening on port 5000"); }
Socket socket = }
serverSocket.accept(); }
InputStream input =
socket.getInputStream();
EXAMPLE: TCP CLIENT-SERVER
● Client code: writer.println("Hello Server!");
import java.io.*; } catch
import java.net.*; (UnknownHostException ex) {
public class SimpleClient { System.out.println("Server not
public static void main(String[] found: " + ex.getMessage());
args) { } catch (IOException ex) {
try (Socket socket = new System.out.println("I/O error: " +
Socket("localhost", 5000)) { ex.getMessage());
OutputStream output = }
socket.getOutputStream(); }
PrintWriter writer = new }
PrintWriter(output, true);
EXERCISE#1
● Modify the simple client-server application to allow
the server to send a response back to the client.
● Tasks:
1. Add code to the server to send a response.
2. Modify the client to receive and display the
server's response.
● Expected Output:
○ Server sends "Hello Client!" to the client.
○ Client displays: "Received from server: Hello
Client!"
UDP COMMUNICATION
● Overview:
○ UDP is faster and more efficient for real-time
applications.
○ Data is sent in packets without establishing a
connection.
● Example:
○ UDP Client-Server Communication.
SIMPLE UDP CLIENT-SERVER
● Server code: String message = new
import java.net.*; String(packet.getData(), 0,
public class UDPServer { packet.getLength());
public static void System.out.println("Received: "
main(String[] args) { + message);
try (DatagramSocket } catch (IOException ex) {
socket = new ex.printStackTrace();
DatagramSocket(5000)) { }
byte[] buffer = new byte[1024]; }
DatagramPacket packet = new }
DatagramPacket(buffer,
buffer.length);
socket.receive(packet);
SIMPLE UDP CLIENT-SERVER
● Client code: DatagramPacket packet
import java.net.*; = new DatagramPacket(buffer,
public class UDPClient { buffer.length, address, 5000);
public static void socket.send(packet);
main(String[] args) { } catch (IOException ex) {
try (DatagramSocket ex.printStackTrace();
socket = new }
DatagramSocket()) { }
byte[] buffer = "Hello }
Server!".getBytes();
InetAddress address =
InetAddress.getByName("local
host");
EXERCISE#2
● Modify the UDP client-server application to allow
two-way communication.
● Tasks:
1. Implement code for the server to send a
response.
2. Modify the client to receive and display the
server's response.
● Expected Output:
○ Server sends "Hello Client!" to the client.
○ Client displays: "Received from server: Hello
Client!
BEST PRACTICES
● Error Handling: Always handle network errors (e.g.,
connection timeouts, unreachable hosts).
● Security: Ensure secure communication using
encryption (e.g., SSL/TLS).
● Resource Management: Always close sockets and
streams to free up resources.
● Concurrency: Handle multiple client connections
using multithreading.
RECAP
● Java provides robust networking support via the
java.net package.
● TCP is reliable but slower, while UDP is faster but
less reliable.
● Understanding the client-server model is crucial for
networking.
● Practical exercises solidify understanding and
application of networking concepts.