Chapter Four Netwk Programming
Chapter Four Netwk Programming
1
CHAPTER FOUR :
NETWORK PROGRAMMING
2
Networking Basics
• Computer networking is to send and receive messages among computers
on the Internet
0 and 255, such as – One domain name can correspond to multiple internet addresses:
[Link], [Link] • [Link]:
[Link], [Link], [Link]; [Link]; [Link]; [Link]; …
4
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.
5
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. 6
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 7
Client server communication
How Java handle such issues
Client
Request
Response
Client
Server
.
.
.
Client
8
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 [Link] 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 [Link] 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.
9
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
OutputStream InputStream
Client Server
InputStream OutputStream 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.
12
Key package and classes
13
Client/Server Communications
The statements needed to create
sockets on a server and a client
are shown below.
14
• 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.
15
• 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.
16
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:
17
Client Sockets
• After a server socket is created, the server can use the following
statement to listen for connections:
Socket socket = [Link]();
• 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.
18
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 [Link] 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.
19
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.
20
Data Transmission through Sockets
21
Data Transmission through Sockets
• To get an input stream and an output stream, use the getInputStream()
and getOutputStream() methods on a socket object.
22
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 following statements, for instance, create the DataInputStream stream input
and the DataOutput stream output to read and write primitive data values:
•The server can use [Link]() to receive a double value from the client, and [Link](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.
23
ServerSocket Class
• The [Link] class is used by server applications to obtain a port and
listen for client requests.
• Constructors
24
Cont.
• 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 [Link] class represents the socket that both the client and server use to
communicate with each other.
29
Cont.
• Notice that both the client and server have a Socket object, so these methods can be
invoked by both the client and server.
30
• InputStream getInputStream() throws IOException: Returns the input stream of the
socket.
• The input stream is connected to the output stream of the remote socket.
• OutputStream getOutputStream() throws IOException: Returns the output stream of
the socket.
• The output stream is connected to the input stream of the remote socket
• void close() throws IOException: Closes the socket, which makes this Socket object no
longer capable of connecting again to any server
31
InetAddress Class
• represents an Internet Protocol (IP) address
• useful methods which you would need while doing socket programming:
• InetAddress getByAddress(byte[] addr): Returns an InetAddress object given the raw IP
address.
• InetAddress getByAddress(String host, byte[] addr): Create an InetAddress based on
the provided host name and IP address.
• InetAddress getByName(String host): Determines the IP address of a host, given the
host's name.
• String getHostAddress(): Returns the IP address string in textual presentation.
• String getHostName() Gets the host name for this IP address.
• InetAddress getLocalHost(): Returns the local host.
• String toString(): Converts this IP address to a String.
32
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
33
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
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 [Link].*;
import [Link].*;
public class GreetingClient {
public static void main(String [] args) {
String serverName = args[0];
int port = [Link](args[1]);
try {
[Link]("Connecting to " +
serverName + " on port " + port);
Socket client = new Socket(serverName, port);
35
[Link]("Just connected to " +
[Link]());
OutputStream outToServer =
[Link]();
DataOutputStream out = new
DataOutputStream(outToServer);
[Link]("Hello from " +
[Link]());
InputStream inFromServer =
[Link]();
DataInputStream in = new
DataInputStream(inFromServer);
[Link]("Server says " +
[Link]());
[Link]();
}catch(IOException e) {
[Link]();
}
} }
36
Socket Server Example:
• The following GreetingServer program is an example of a server
application that uses the Socket class to listen for clients on a port
number specified by a command-line argument:
import [Link].*;
import [Link].*;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
[Link](10000);
}
37
public void run() {
while(true) {
try {
[Link]("Waiting for client on port " +
[Link]() + "...");
Socket server = [Link]();
[Link]("Just connected to " +
[Link]());
DataInputStream in = new
DataInputStream([Link]());
[Link]([Link]());
DataOutputStream out = new
DataOutputStream([Link]());
[Link]("Thank you for connecting to " +
[Link]() + "\nGoodbye!");
[Link]();
}
38
catch(SocketTimeoutException s) {
[Link]("Socket timed out!");
break;
}catch(IOException e) {
[Link]();
break;
}
}
}
public static void main(String [] args) {
int port = [Link](args[0]);
try {
Thread t = new GreetingServer(port);
[Link]();
}catch(IOException e) {
[Link]();
}}}
39
UDP Clients and Servers
41
import [Link].*; import [Link].*;
import [Link].*; import [Link].*;
DatagramSocket serverSocket = new DatagramSocket(1234); // create a byte array to hold the message to send
[Link]("UDP Server is running on port " + String message = "Hello, server!";
[Link]());
byte[] sendData = [Link]();
// create a byte array to hold incoming data InetAddress serverAddress = [Link]("localhost");
byte[] receiveData = new byte[1024]; int serverPort = 1234;
// create a DatagramPacket to receive incoming packets DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
serverAddress, serverPort); // create a DatagramPacket to send to the server
DatagramPacket receivePacket = new DatagramPacket(receiveData,
[Link]); [Link](sendPacket); // send the packet to the server
while (true) { // wait for incoming packets [Link](receivePacket); [Link]("Sent message: " + message + " to " + serverAddress + ":" +
43
cont…
44
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.
45
• 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.
46
Example of Sending DatagramPacket
by DatagramSocket
import [Link].*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = [Link]("[Link]");
DatagramPacket dp = new DatagramPacket([Link](),
[Link](), ip, 3000);
[Link](dp);
[Link]();
}
}
47
Example of Receiving
DatagramPacket by DatagramSocket
import [Link].*;
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);
[Link](dp);
String str = new String([Link](), 0, [Link]());
[Link](str);
[Link]();
}
}
48
URL
• The Web is a loose collection of higher-level protocols and file formats, all
unified in a web browser.
• Once you can reliably name anything and everything, it becomes a very
powerful paradigm. The Uniform Resource Locator (URL) does exactly that.
• The URL provides a reasonably intelligible form to uniquely identify or
address information on the Internet.
• URLs are ubiquitous; every browser uses them to identify information on the
Web.
• Within Java’s network class library, the URL class provides a simple, concise
API to access information across the Internet using URLs.
49
• Format
• A URL specification is based on four components:
• The first is the protocol to use, separated from the rest of the locator by a colon (:).
• The second component is the host name or IP address of the host to use; this is
delimited on the left by double slashes (//) and on the right by a slash (/) or
optionally a colon (:).
• The third component, the port number, is an optional parameter, delimited on the
left from the host name by a colon (:) and on the right by a slash (/).
• The fourth part is the actual file path.
• Java’s URL class has several constructors, and each can throw a
MalformedURLException.
• One commonly used form specifies the URL with a string that is identical to
what you see displayed in a browser:
• URL(String urlSpecifier)
50
• 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)
51
• Commonly used methods of Java URL class
• The [Link] 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.
52
• In the following example, we create a URL to SW web page and then examine its
properties:
import [Link].*;
class URLDemo {
public static void main(String args[]) throws
MalformedURLException {
53
• output:
• Protocol: http
• Port: -1
• Host: [Link]
• File: /[Link]/about-sw/
• Ext:[Link]
54
URLConnection Class
• represents a communication link between the URL and the application.
• This class can be used to read and write data to the specified resource
referred by the URL.
• The openConnection() method of URL class returns the object of
URLConnection class.
• Syntax:
public URLConnection openConnection()throws IOException{}
55
Example of Java URLConnecton class
import [Link].*;
import [Link].*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("[Link]
URLConnection urlcon=[Link]();
InputStream stream=[Link]();
int i;
while((i=[Link]())!=-1){
[Link]((char)i);
}
}catch(Exception e){[Link](e);}
}
}
56
HttpURLConnection class
• is http specific URLConnection. It works for HTTP protocol only.
• By the help of HttpURLConnection class, you can get information of any
HTTP URL such as header information, status code, response code etc.
• The [Link] is subclass of URLConnection class.
• How to get the object of HttpURLConnection class
• Get the URLConnection object using openConnection() method
• URLConnection openConnection(){}
• Typecast this object to HttpURLConnection type
• URL url=new URL("[Link]
• HttpURLConnection huc=(HttpURLConnection)[Link]();
57
HttpURLConnecton Example
import [Link].*;
import [Link].*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("[Link]
HttpURLConnection huc=(HttpURLConnection)[Link]();
for(int i=1;i<=8;i++){
[Link] ([Link](i) + " = " +
[Link](i));
}
[Link]();
}catch(Exception e){[Link](e);}
}
}
58
Serving Multiple Clients
59
Cont…
▪ Here is how the server handles the establishment of a
connection:
60
Example: Serving Multiple Clients
61
Example: Serving Multiple
•
Clients
import [Link].*; import [Link].*; import [Link].*; import
[Link].*; import [Link].*;
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), [Link]);
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);
[Link]("MultiThreadServer started at " + new Date() + '\n' );
// Number a client int clientNo = 1;
62
Example: Serving Multiple
• Clients
while (true) {
// Listen for a new connection request
Socket socket = [Link]();
// Display the client number
[Link]("Starting thread for client " + clientNo +
" at " + new Date() + '\n' );
// Find the client's host name and IP address InetAddress
inetAddress = [Link]();
[Link]("Client " + clientNo + "'s host name is “
+ [Link]() + "\n");
[Link]("Client " + clientNo + "'s IP Address is “
+ [Link]() + "\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) {
[Link](ex);
}
}
63
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) {
[Link] = socket;
}
}
• You
Sending
can also
and Receiving Objects
send ObjectOutputStream on socket streams.
information from a
[Link]() [Link](student)
client and send them to
a server. Passing in: ObjectInputStream out: ObjectOutputStream
student information in
an object. [Link] [Link]
socket socket
Network
66
Example: Passing Objects in
Network Programs
public class StudentAddress implements [Link] {
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) {
[Link] = name; [Link] = street; [Link] = city; [Link]
= state; [Link] = zip;
}
public String getName() {
return name;
}
public String getStreet() {
return street; public return String getCity() {
}
city;
}
state; public return String getState() {
}
zip;
}
public return String getZip() {
34
}
Example: Passing Objects in
Network Programs
import [Link].*; import [Link].*; import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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(); [Link](new GridLayout(3, 1)); [Link](new
JLabel("Name")); [Link](new JLabel("Street")); [Link](new
JLabel("City"));
35
Example: Passing Objects in Network Programs
// Panel jpState for holding state JPanel jpState = new
JPanel(); [Link](new BorderLayout());
[Link](new JLabel("State"),
[Link]);
[Link](jtfState, [Link]);
// Panel jpZip for holding zip
JPanel jpZip = new JPanel();
[Link](new BorderLayout()); [Link](new
JLabel("Zip"), [Link]); [Link](jtfZip,
[Link]);
[Link](jtfCity,
[Link]);
36
Example: Passing Objects in
• Network Programs
[Link](p2, [Link]);
// Panel p4 for holding jtfName, jtfStreet, and p3
JPanel p4 = new JPanel(); [Link](new GridLayout(3, 1));
[Link](jtfName);
[Link](jtfStreet);
[Link](p3);
// Place p1 and p4 into StudentPanel
JPanel studentPanel = new JPanel(new BorderLayout());
[Link](new BevelBorder([Link]));
[Link](p1, [Link]);
[Link](p4, [Link]);
// Add the student panel and button to the applet
add(studentPanel, [Link]); add(jbtRegister,
[Link]);
// Register listener
[Link](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);
70
Example: Passing Objects in
Network
// Create an Programs
output stream to the server
ObjectOutputStream toServer = new
ObjectOutputStream([Link]());
// Get text field
String name = [Link]().trim(); String
street = [Link]().trim(); String city =
[Link]().trim(); String state =
[Link]().trim(); String zip =
[Link]().trim();
// Create a StudentAddress object and send to the
server StudentAddress s =
new StudentAddress(name, street, city, state,
zip);
[Link](s);
}
catch (IOException ex) { [Link](ex);
}
}
}
71
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(); [Link] = true;
// Get host
if ([Link] == 1) [Link] = args[0];
// Add the applet instance to the frame
[Link](applet, [Link]);
// Invoke init() and start() [Link](); [Link]();
// Display the frame [Link](); [Link](true);
}
}
72
Example: Passing Objects in
Network Programs
• import [Link].*;
import [Link].*;
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); [Link]("Server started ");
while (true) {
// Listen for a new connection request
Socket socket = [Link]();
73
Example: Passing Objects in
// Network
Read from inputPrograms
Object object = [Link]();
// Write to the file [Link](object);
[Link]("A new student object is stored");
}
}
catch(ClassNotFoundException ex) { [Link]();
}
catch(IOException ex) { [Link]();
}
finally {
try { [Link](); [Link]();
}
catch (Exception ex) { [Link]();
}
}
}
}
74