0% found this document useful (0 votes)
79 views

CH 4 - Java Networking Weekend

This document provides an overview of networking concepts in Java, including: 1) It describes key networking terms like TCP, IP, domain names, and domain name servers and explains how they enable communication between computers on the Internet. 2) It explains how to create client and server sockets in Java to establish connections between applications and transmit data over the network. 3) It provides an example client-server application where the client sends a radius to the server, which calculates the area and sends it back to the client.

Uploaded by

Belay Barane
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

CH 4 - Java Networking Weekend

This document provides an overview of networking concepts in Java, including: 1) It describes key networking terms like TCP, IP, domain names, and domain name servers and explains how they enable communication between computers on the Internet. 2) It explains how to create client and server sockets in Java to establish connections between applications and transmit data over the network. 3) It provides an example client-server application where the client sends a radius to the server, which calculates the area and sends it back to the client.

Uploaded by

Belay Barane
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter-4

Networking in Java

By the end of this chapter, you will be able:


• To explain terms: TCP, IP, domain name, domain name server, stream based
communications, and packet-based communications

• To create servers using server sockets and clients using client Sockets

• To implement Java networking programs using stream sockets

• To develop an example of a client/server application

• To obtain Internet addresses using the InetAddress class.

• To develop servers for multiple clients

1
Introduction
Computer networking is used to send and receive messages among computers on the
Internet.

When a computer needs to communicate with another computer, it needs to know the
other computer’s address.

An Internet Protocol (IP) address uniquely identifies the computer on the Internet.

An IP address consists of four dotted decimal numbers between 0 and 255, such as
130.254.204.31.

Since it is not easy to remember so many numbers, they are often mapped to
meaningful names called domain names, such as www.wsu.edu.et

Special servers called Domain Name Servers (DNS) on the Internet translate host
names into IP addresses.
When a computer contacts www.wsu.edu.et , it first asks the DNS to translate this
domain name into a numeric IP address and then sends the request using the IP
address. 2
The Internet Protocol is a low-level protocol for delivering data from one computer to
another across the Internet in packets.

Two higher-level protocols used in conjunction with the IP are the Transmission Control
Protocol (TCP) and the User Datagram Protocol (UDP).

TCP enables two hosts to establish a connection and exchange streams of data.
TCP guarantees delivery of data and also guarantees that packets will be delivered in
the same order in which they were sent.

UDP is a standard, low-overhead, connectionless, host-to-host protocol that is used over


the IP.

UDP allows an application program on one computer to send a datagram to an


application program on another computer.

Java supports both stream-based and packet-based communications.

Stream-based communications use TCP for data transmission, whereas packet-based


communications use UDP. 3
Since TCP can detect lost transmissions and resubmit them, transmissions are lossless
and reliable.

Stream-based communications are used in most areas of Java programming UDP, in


contrast, cannot guarantee lossless transmission.

Client/Server Computing
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.

Java treats socket communications much as it treats I/O operations; thus, programs can
read from or write to sockets as easily as they can read from or write to files.

Network programming usually involves a server and one or more clients.


The client sends requests to the server, and the server responds.

4
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.
TCP Sockets
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.

Port numbers range from 0 to 65536, but port numbers 0 to 1024 are reserved for
privileged services.

For instance, the email server runs on port 25, and the Web server usually runs on port
80.
You can choose any port number that is not currently used by other programs. The
following statement creates a server socket serverSocket:
ServerSocket serverSocket = new ServerSocket(port); 5
Note
Attempting to create a server socket on a port already in use would cause a
java.net.BindException.

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.
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:
Socket socket = new Socket("130.254.204.33", 8000)
Alternatively, you can use the domain name to create a socket, as follows:
Socket socket = new Socket(“www.wsu.edu.et ", 8000);
6
When you create a socket with a host name, the JVM asks the DNS to translate the host
name into the IP address.

Note
A program can use the host name localhost or the IP address 127.0.0.1 to refer to
the machine on which a client is running.

The Socket constructor throws a java.net.UnknownHostException if the host


cannot be found.

In general, as shown in the figure below, the server creates a server socket and, once a
connection to a client is established, connects to the client with a client socket.

7
After the server accepts the connection, communication between the server and the
client is conducted in the same way as for I/O streams.

The statements needed to create the streams and to exchange data between them are
shown in the following figure

8
To get an input stream and an output stream, use the getInputStream() and
getOutputStream() methods on a socket object.

For example, the following statements create an InputStream stream called input
and an OutputStream stream called output from a socket:

InputStream input = socket.getInputStream();


OutputStream output = socket.getOutputStream();

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, or String.

The following statements, for instance, create the DataInputStream stream input
and the DataOutputStream stream output to read and write primitive data values:

DataInputStream input = new DataInputStream


(socket.getInputStream());

DataOutputStream output = new DataOutputStream


(socket.getOutputStream());
9
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.

Tip
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.

A Client/Server Example
The client sends the radius to the server; the server computes the area and sends it to
the client as shown below.

(a) The client sends the radius to the server. (b) The server sends the area to the client.

10
//server code
import java.io.*;
import java.net.*;
import java.util.*;
public class ServerArea {

private static ServerSocket serverSocket;


private static int PORT=8000;
private static DataInputStream inputFromClient = null;
private static DataOutputStream outputToClient = null;
public static void main(String [] args){
System.out.println("Opening port...\n");
try {
// Create a server socket
serverSocket = new ServerSocket(PORT);

System.out.println("Server started at " + new Date() + '\n');


}
catch(IOException ioEx)
{
System.out.println("Unable to attach to port!");
System.exit(1);
}
11
do
{
handleClient();
}while (true);
}

private static void handleClient()


{
Socket link = null;
try{
// Listen for a connection request
link = serverSocket.accept();

// Create data input and output streams


inputFromClient = new DataInputStream(link.getInputStream());
outputToClient = new DataOutputStream(link.getOutputStream());

int numRequest=0;
double radius = inputFromClient.readDouble();
while (radius!=0) {

12
// Compute area
double area = radius * radius * Math.PI;
numRequest++;
// Send area back to the client
outputToClient.writeDouble(area);
System.out.println("Request number : " + numRequest + '\n');
System.out.println("Radius received from client: " + radius +
'\n');
System.out.printf("Area is: %.2f %s" , area , "\n");

// Receive radius from the client


radius = inputFromClient.readDouble();
}
}
catch(IOException ex) {
//ex.printStackTrace();
System.out.println("Client disconnected");
}
finally{
try{
System.out.println("Closing connection...");
link.close();

13
}catch(IOException ioEx)
{
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}

14
//client code
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ClientArea{
// IO streams
private static DataOutputStream toServer = null;
private static DataInputStream fromServer = null;
//Socket instance
private static Socket socket;
private static int PORT=8000;
private static String serverName="localhost";
private static Scanner in = new Scanner(System.in);
private static double radius;
private static double area;
public static void main(String []args){
System.out.println("Client running");

accessServer();
}

15
public static void accessServer(){
try {
// Create a socket to connect to the server
socket = new Socket(serverName, PORT);
// Socket socket = new Socket("192.168.1.34", 8000);
// Socket socket = new Socket("wsu.edu.et", 8000);

// Create an input stream to receive data from the server


fromServer = new DataInputStream(socket.getInputStream());

// Create an output stream to send data to the server


toServer = new DataOutputStream(socket.getOutputStream());
System.out.println("Enter a radius [0 to quit]: ");
radius = in.nextDouble();
while(radius!=0){
// Send the radius to the server
toServer.writeDouble(radius);
toServer.flush();

// Get area from the server


area = fromServer.readDouble();

16
// Display the text
System.out.println("Radius is " + radius + "\n");
System.out.println("Area received from the server is "+ area +
'\n');
// Get the radius from the text field
System.out.println("Enter a radius [0 to quit]: ");
radius = in.nextDouble();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
finally{
try{
System.out.println("\n* Closing connection… *");
socket.close();
}catch(IOException ie){
System.out.println("Unable to disconnect!");
System.exit(1);
}

} 17
}
You start the server program first and then start the client program.
In the client program, enter a radius and press Enter to send the radius to the server.

The server computes the area and sends it back to the client.

This process is repeated until one of the two programs terminates.

The networking classes are in the package java.net. You should import this package
when writing Java network programs.

Note
When you create a server socket, you have to specify a port (e.g., 8000) for the socket.

When a client connects to the server , a socket is created on the client.


This socket has its own local port. This port number (e.g., 2047) is automatically
chosen by the JVM, as shown in the following figure

18
Serving Multiple Clients
Typically, a server runs continuously on a server computer, and clients from all over the
Internet can connect to it.

You can use threads to handle the server’s multiple clients simultaneously

For this to happen, the main loop of the server should look like this:
while (true)
{
Socket incoming = serverSocket.accept();

Runnable r = new ThreadedHandler(incoming);


Thread t = new Thread(r);
t.start();
}

19
Or
while (true) {
Socket socket = serverSocket.accept(); // Connect to a client
Thread thread = new ThreadClass(socket);
thread.start();
}
The server socket can have many connections.
Each iteration of the while loop creates a new connection.
Whenever a connection is established, a new thread is created to handle communication
between the server and the new client, and this allows multiple connections to run at the
same time; As shown below

20

You might also like