Chapter 4 Network Programming 2025
Chapter 4 Network Programming 2025
Network Programming
1
Networking Basics
• Computer networking is to send and receive messages among
computers on the Internet
• To browse the Web or send email, your computer must be
connected to the Internet.
• Your computer can connect to the Internet through an Internet
Service Provider (ISP) using a dialup, DSL, or cable modem, or
through a local area network (LAN).
• Java Networking is a concept of connecting two or more
computing devices together so that we can share resources.
• Advantage of Java Networking
– sharing resources
– centralize software management
• When a computer needs to communicate with another computer,
it needs to know an IP address.
2
Networking Basics
• Internet Protocol (IP) addresses
– Uniquely identifies the computer on the Internet. or
– IP address is a unique number assigned to a node of a network.
– It is a logical address that can be changed.
– Every host on Internet has a unique IP address
– An IP address consists of four dotted decimal numbers ranging from
0 and 255, such as
143.89.40.46, 203.184.197.198
203.184.197.196, 203.184.197.197, 127.0.0.
– Since it is difficult to remember IP address, there is a special server
called Domain Name Server(DNS), which translates hostname to IP
address
– Example: DomainName: www.google.com, localhost
IPAddresess: 216.58.207.4 127.0.0.1
– One domain name can correspond to multiple internet addresses:
• www.yahoo.com:
66.218.70.49; 66.218.70.50; 66.218.71.80; 66.218.71.84; …
– Domain Naming Service (DNS) maps names to numbers
3
Networking Basics
Port Number
The port number is used to uniquely identify different applications.
It acts as a communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
Port numbers are ranging from 0 to 65536, but port numbers 0 to 1024 are
reserved for privileged services.
Many standard port numbers are pre-assigned
time of day 13, ftp 21, telnet 23, smtp 25, http 80
You can choose any port number that is not currently used by other programs.
IP address + port number = "phone number“ for service or application
MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller).
A network node can have multiple NIC but each with unique MAC. 4
Networking Basics
A protocols is a set of rules that facilitate communications between machines or hosts.
Examples:
HTTP: HyperText Transfer Protocol
FTP: File Transfer Protocol
SMTP: Simple Message Transfer Protocol
TCP: Transmission Control Protocol
UDP: User Datagram Protocol, good for, e.g., video delivery)
TCP:
Connection-oriented protocol
enables two hosts to establish a connection and exchange streams of data.
Acknowledgement is send by the receiver. So, it is reliable but slow
Uses Stream-based communications
guarantees delivery of data and also guarantees that packets will be delivered in the same
order in which they were sent.
UDP:
Enables connectionless communication
Acknowledgement is not sent by the receiver. So it is not reliable but fast.
Uses packet-based communications.
Cannot guarantee lossless transmission.
5
Networking Basics
Client-Server interaction
Communication between hosts is two-way, but usually the two hosts take different
roles.
Server waits for client to make request
Server registered on a known port with the host ("public phone number") Listens for incoming client
connections
Server offers shared resource (information, database, files, printer, compute power)
to clients
6
Client server communication
How Java handle such issues
Client
Request
Response
Client
Server
.
.
.
Client
7
Introduction
• network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using
a network.
• The java.net package of the J2SE(Java 2 Platform, Standard Edition) APIs
contains a collection of classes and interfaces that provide the low-level
communication details
• The java.net package provides support for the two common network
protocols:
• TCP: allows for reliable communication between two applications.
• is typically used over the Internet Protocol, which is referred to as TCP/IP.
• UDP: is a connection-less protocol that allows for packets of data to be transmitted
between applications.
8
Socket-Level Programming
Java Socket programming is used for communication between the applications
running on different JRE.
Java Socket programming can be connection-oriented or connection-
less.
Socket and ServerSocket classes are used for connection-oriented socket
programming.
DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
Java socket programming provides facility to share data between different
computing devices.
Send and receive data using streams
OutputStr InputStr
eam eam
Client Server
InputStr OutputStr 7
TCP
• Java provides the ServerSocket class for creating a server socket and the Socket class for creating a client
socket.
• Two programs on the Internet communicate through a server socket and a client socket using I/O streams.
• Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data.
• Network programming usually involves a server and one or more clients.
• The client sends requests to the server, and the server responds.
• The client begins by attempting to establish a connection to the server.
• The server can accept or deny the connection.
• Once a connection is established, the client and the server communicate through sockets.
• The server must be running when a client attempts to connect to the server.
• When the connection is made, the server creates a socket object on its end of
the communication.
• The client and server can now communicate by writing to and reading from
the socket.
12
• The following steps occur when establishing a TCP
connection between two computers using sockets:
• The server instantiates a ServerSocket object, denoting which port number communication
is to occur on.
• The server invokes the accept() method of the ServerSocket class. This method waits until a
client connects to the server on the given port.
• After the server is waiting, a client instantiates a Socket object, specifying the server name
and port number to connect to.
• The constructor of the Socket class attempts to connect the client to the specified server and
port number.
• If communication is established, the client now has a Socket object capable of communicating with
the server.
• 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.
13
• After the connections are established, communication can occur using I/O
streams.
• Each socket has both an OutputStream and an InputStream.
• The client's OutputStream is connected to the server's InputStream, and
• The client's InputStream is connected to the server's OutputStream.
• TCP is a two way communication protocol, so data can be sent across both
streams at the same time.
14
Server Sockets
• To establish a server, you need to create a server socket and
attach it to a port, which is where the server listens for
connections.
• The port identifies the TCP service on the socket.
• The following statement creates a server socket
serverSocket:
15
Client Sockets
• After a server socket is created, the server can use the following
statement to listen for connections:
Socket socket = serverSocket.accept();
• This statement waits until a client connects to the server socket.
• The client issues the following statement to request a connection
to a server:
Socket socket = new Socket(serverName, port);
• This statement opens a socket so that the client program can
communicate with the server.
16
Client Sockets
• serverName is the server’s Internet host name or IP address.
• The following statement creates a socket on the client machine
to connect to the host 130.254.204.33 at port 8000:
• When you create a socket with a host name, the JVM asks the
DNS to translate the host name into the IP address.
17
Data Transmission through
Sockets
• After the server accepts the connection, communication
between the server and client is conducted the same as for
I/O streams.
18
Data Transmission through
Sockets
19
Data Transmission through
Sockets
• To get an input stream and an output stream, use the getInputStream()
and getOutputStream() methods on a socket object.
20
Data Transmission through Sockets
• The InputStream and OutputStream streams are used to read or
write bytes.
• You can use DataInputStream, DataOutputStream,
BufferedReader, and PrintWriter to wrap on the InputStream and
OutputStream to read or write data, such as int, double, orString.
•The server can use input.readDouble() to receive a double value from the client, and
output.writeDouble(d) to send the double value d to the client.
•Binary I/O is more efficient than text I/O because text I/O requires encoding and
decoding.
•Therefore, it is better to use binary I/O for transmitting data between a server and a
client to improve performance. 21
A Client/Server Example
• Problem: Write a client and a server program that the
client sends data to a server. The server receives the data,
uses it to produce a result, and then sends the result back
to the client. The client displays the result on the console.
In this example, the data sent from the client is the radius
of a circle, and the result produced by the server is the
area of the circle. The client sends the radius to the
server; the server computes the area and sends it to the
client.
compute area
radius
Server Client
area
22
A Client/Server Example
• The client sends the radius through a DataOutputStream on the output stream
socket, and the server receives the radius through the DataInputStream on the
input stream socket, as shown in Figure (A) below.
• The server computes the area and sends it to the client through a
DataOutputStream on the output stream socket, and the client receives the
area through a DataInputStream on the input stream socket, as shown in
Figure (B) below.
Network Network
(A) (B) 18
ServerSocket Class
• The java.net.ServerSocket class is used by server applications to obtain a
port and listen for client requests.
• Constructors
• Common Methods
• int getLocalPort(): Returns the port that the server socket is listening on.
• This method is useful if you passed in 0 as the port number in a constructor and let the
server find a port for you.
• Socket accept(): Waits for an incoming client.
• This method blocks until either a client connects to the server on the specified port or the
socket times out, assuming that the time-out value has been set using the
setSoTimeout() method Otherwise, this method blocks indefinitely
25
Cont.
• 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(SocketAddress host, int backlog): Binds the socket to the
specified server and port in the SocketAddress object.
• Use this method if you instantiated the ServerSocket using the no-argument constructor.
26
Socket Class
• The java.net.Socket class represents the socket that both the client and server
use to communicate with each other.
• The client obtains a Socket object by instantiating one, whereas the server
obtains a Socket object from the return value of the accept() method.
27
Java Sockets
31
InetAddress Class
32
Socket Client Example:
• The following GreetingClient is a client program that connects to
a server by using a socket and sends a greeting, and then waits
for a response.
import java.net.*;
import java.io.*;
public class GreetingClient {
public static void main(String [] args) {
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Connecting to " +
serverName + " on port " + port);
Socket client = new Socket(serverName, port);
33
System.out.println("Just connected to " +
client.getRemoteSocketAddress());
OutputStream outToServer =
client.getOutputStream();
DataOutputStream out = new
DataOutputStream(outToServer);
out.writeUTF("Hello from " +
client.getLocalSocketAddress());
InputStream inFromServer =
client.getInputStream();
DataInputStream in = new
DataInputStream(inFromServer);
System.out.println("Server says " +
in.readUTF());
client.close();
}catch(IOException e) {
e.printStackTrace();
}
} }
34
Socket Server Example:
}catch(IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String [] args) {
int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e) {
e.printStackTrace();
}}}
37
UDP Clients and Servers
39
import java.io.*; import java.net.*;
import java.io.*; import java.net.*;
DatagramSocket serverSocket = new DatagramSocket(1234); // create a byte array to hold the message to send
System.out.println("UDP Server is running on port " + serverSocket.getLocalPort()); String message = "Hello, server!";
// create a byte array to hold incoming data byte[] sendData = message.getBytes();
byte[] receiveData = new byte[1024]; InetAddress serverAddress = InetAddress.getByName("localhost");
SERVER
clientAddress + ":" + clientPort);
// create a DatagramPacket to receive the response from the server DatagramPacket
// send a response to the client receivePacket = new DatagramPacket(receiveData, receiveData.length);
String response = "Hello, client!"; // wait for the response from the server clientSocket.receive(receivePacket);
// extract the data from the packet
byte[] sendData = response.getBytes();
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress,
clientPort); serverSocket.send(sendPacket); InetAddress server = receivePacket.getAddress();
System.out.println("Sent message: " + response + " to " + clientAddress + ":" + clientPort); int port = receivePacket.getPort(); System.out.println("Received message: " + response
+ " from " + server + ":" + port); // close the socket clientSocket.close();
} } catch (IOException e) {
} e.printStackTrace();
catch (IOException e) { }
e.printStackTrace(); }
}
}
DatagramSocket and DatagramPacket
• Java DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.
• DatagramSocket class
• represents a connection-less socket for sending and receiving datagram
packets.
• A datagram is basically an information but there is no guarantee of its
content, arrival or arrival time.
• Commonly used Constructors of DatagramSocket class
• DatagramSocket() throws SocketException: it creates a datagram socket
and binds it with the available Port Number on the localhost machine.
• DatagramSocket(int port) throws SocketException: it creates a datagram
socket and binds it with the given Port Number.
• DatagramSocket(int port, InetAddress address) throws SocketException:
it creates a datagram socket and binds it with the specified port number and
host address.
41
• DatagramPacket class
• is a message that can be sent or received.
• If you send multiple packet, it may arrive in any order. Additionally, packet
delivery is not guaranteed.
• Commonly used Constructors of DatagramPacket class
• DatagramPacket(byte[] barr, int length): it creates a datagram packet. This
constructor is used to receive the packets.
• DatagramPacket(byte[] barr, int length, InetAddress address, int port): it
creates a datagram packet. This constructor is used to send the packets.
42
Example of Sending DatagramPacket by
DatagramSocket
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(),
str.length(), ip, 3000);
ds.send(dp);
ds.close();
}
}
43
Example of Receiving DatagramPacket by
DatagramSocket
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
44
• start server as follows:
• $ java GreetingServer 6000
45
URL
47
• The next two forms of the constructor allow you to break up the URL into
its component parts:
• URL(String protocolName, String hostName, int port,
String path)
• URL(String protocolName, String hostName, String path)
• Another frequently used constructor allows you to use an existing URL as
a reference context and then create a new URL from that context.
• URL(URL urlObj, String urlSpecifier)
48
• Commonly used methods of Java URL class
• The java.net.URL class provides many methods. The important methods
of URL class are given below.
Method Description
• public String getProtocol() it returns the protocol of the
URL.
• public String getHost() it returns the host name of the
URL.
• public String getPort() it returns the Port Number of the
URL.
• public String getFile() it returns the file name of the
URL.
• public URLConnection it returns the instance of openConnection()
URLConnection i.e associated with this URL. 49
• In the following example, we create a URL to SW web page and then examine its
properties:
import java.net.*;
class URLDemo {
public static void main(String args[]) throws
MalformedURLException {
57
Example: Serving Multiple Clients
58
Example: Serving Multiple Clients
• import java.io.*; import java.net.*; import java.util.*; import
java.awt.*; import javax.swing.*;
public class MultiThreadServer extends JFrame {
// Text area for displaying contents private JTextArea jta = new
JTextArea();
public static void main(String[] args) {
new MultiThreadServer();
}
public MultiThreadServer() {
// Place text area on the frame
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("MultiThreadServer");
setSize(500, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("MultiThreadServer started at " + new Date() + '\n' );
// Number a client int clientNo = 1;
59
Example: Serving Multiple Clients
• while (true) {
// Listen for a new connection request
Socket socket = serverSocket.accept();
// Display the client number
jta.append("Starting thread for client " + clientNo +
" at " + new Date() + '\n' );
// Find the client's host name and IP address InetAddress
inetAddress = socket.getInetAddress();
jta.append("Client " + clientNo + "'s host name is “
+ inetAddress.getHostName() + "\n");
jta.append("Client " + clientNo + "'s IP Address is “
+ inetAddress.getHostAddress() + "\n");
// Create a new thread for the connection
HandleAClient task = new HandleAClient(socket);
// Start the new thread
new Thread(task).start();
// Increment clientNo
clientNo++;
}
}
catch(IOException ex) {
System.err.println(ex);
}
}
60
Example: Serving Multiple Clients
// Inner class
// Define the thread class for handling new
connection class HandleAClient implements Runnable {
private Socket socket; // A connected socket
/** Construct a thread */
public HandleAClient(Socket socket) {
this.socket = socket;
}
}
Sending and Receiving Objects
• You can also send ObjectOutputStream on socket streams.
• A program can send and receive objects from
another program.
• In the preceding examples, you learned how to
send and receive data of primitive types.
and receive objects
using and
ObjectInputStream
• To enable passing, the objects must be
serializable.
• The following example demonstrates how to send
and receive objects. 62
Example: Passing Objects in Network
Programs
information from a
in.readObject() out.writeObject(student)
client and send them to
a server. Passing in: ObjectInputStream out: ObjectOutputStream
student information in
an object. socket.getInputStream socket.getOutputStream
socket socket
Network
63
Example: Passing Objects in Network
Programs
public class StudentAddress implements java.io.Serializable {
private String name; private String street; private String city;
private String state; private String zip;
public StudentAddress(String name, String street, String city, String
state, String zip) {
this.name = name; this.street = street; this.city = city; this.state
= state; this.zip = zip;
}
public String getName() {
return name;
}
public String getStreet() {
return street;
}
city;
state;
} publi String getCity() {
c
retur
zip;
} n
} 34
publi String getState() {
c
retur
n
publi String getZip() {
Example: Passing Objects in Network
import java.io.*;Programs
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class StudentClient extends JApplet {
private JTextField jtfName = new
JTextField(32); private JTextField
jtfStreet = new JTextField(32); private
JTextField jtfCity = new JTextField(20);
private JTextField jtfState = new
JTextField(2); private JTextField jtfZip =
new JTextField(5);
// Button for sending a student's address to
the server private JButton jbtRegister =
new JButton("Register to the Server");
// Indicate if it runs as application
private boolean isStandAlone = false;
// Host name or IP address String host =
"localhost"; public void init() {
// Panel p1 for holding labels Name, Street,
and City
JPanel p1 = new JPanel(); p1.setLayout(new
Example: Passing Objects in Network Program
// Panel jpState for holding state JPanel
jpState = new JPanel(); jpState.setLayout(new
BorderLayout()); jpState.add(new
JLabel("State"),
BorderLayout.WEST);
jpState.add(jtfState, BorderLayout.CENTER);
// Panel jpZip for holding zip
JPanel jpZip = new JPanel();
jpZip.setLayout(new BorderLayout());
jpZip.add(new JLabel("Zip"),
BorderLayout.WEST); jpZip.add(jtfZip,
BorderLayout.CENTER);
// Panel p2 for holding jpState and jpZip
JPanel p2 = new JPanel(); p2.setLayout(new
BorderLayout()); p2.add(jpState,
BorderLayout.WEST); p2.add(jpZip,
BorderLayout.CENTER);
// Panel p3 for holding jtfCity and p2 JPanel
p3 = new JPanel(); p3.setLayout(new
p3.add(jtfCity,
BorderLayout()); 36
Example: Passing Objects in Network
• Programs
p3.add(p2, BorderLayout.EAST);
// Panel p4 for holding jtfName, jtfStreet, and p3
JPanel p4 = new JPanel(); p4.setLayout(new GridLayout(3, 1));
p4.add(jtfName);
p4.add(jtfStreet);
p4.add(p3);
// Place p1 and p4 into StudentPanel
JPanel studentPanel = new JPanel(new BorderLayout());
studentPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
studentPanel.add(p1, BorderLayout.WEST);
studentPanel.add(p4, BorderLayout.CENTER);
// Add the student panel and button to the applet
add(studentPanel, BorderLayout.CENTER); add(jbtRegister,
BorderLayout.SOUTH);
// Register listener
jbtRegister.addActionListener(new ButtonListener());
// Find the IP address of the Web server
if (!isStandAlone)
host = getCodeBase().getHost();
}
/** Handle button action */
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
// Establish connection with the server
Socket socket = new Socket(host, 8000);
67
Example: Passing Objects in Network
Programs
// Create an output stream to the server
ObjectOutputStream toServer = new
ObjectOutputStream(socket.getOutputStream());
// Get text field
String name = jtfName.getText().trim(); String
street = jtfStreet.getText().trim(); String city =
jtfCity.getText().trim(); String state =
jtfState.getText().trim(); String zip =
jtfZip.getText().trim();
// Create a StudentAddress object and send to the
server StudentAddress s =
new StudentAddress(name, street, city, state,
zip);
toServer.writeObject(s);
}
catch (IOException ex) { System.err.println(ex);
}
}
}
68
Example: Passing Objects in Network
Programs
/** Run the applet as an application */
public static void main(String[] args)
{
// Create a frame
JFrame frame = new JFrame("Register
Student Client");
// Create an instance of the applet
StudentClient applet = new
StudentClient(); applet.isStandAlone
= true;
// Get host
if (args.length == 1) applet.host =
args[0];
// Add the applet instance to the frame
frame.add(applet, BorderLayout.CENTER);
// Invoke init() and start()
applet.init(); applet.start();
// Display the frame frame.pack(); 69
Example: Passing Objects in Network
• Programs
import java.io.*;
import java.net.*;
public class StudentServer {
private ObjectOutputStream outputToFile;
private ObjectInputStream
inputFromClient; public static void
main(String[] args) { new
StudentServer();
}
public StudentServer() {
try {
// Create a server socket
ServerSocket serverSocket = new
ServerSocket(8000);
System.out.println("Server started
");
// Create an object output stream
outputToFile = new ObjectOutputStream(
new FileOutputStream("student.dat",
true));
while (true) { 70
Example: Passing Objects in Network
Programs
// Read from input
Object object =
inputFromClient.readObject();
// Write to the file
outputToFile.writeObject(object);
System.out.println("A new student object
is stored");
}
}
catch(ClassNotFoundException ex) {
ex.printStackTrace();
}
catch(IOException ex) {
ex.printStackTrace();
}
finally {
try { inputFromClient.close();
outputToFile.close();
}
catch (Exception ex) {
ex.printStackTrace();
} 71