CH 4 - Java Networking Weekend
CH 4 - Java Networking Weekend
Networking in Java
• To create servers using server sockets and clients using client Sockets
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.
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.
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.
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 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.
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:
The InputStream and OutputStream streams are used to read or write bytes.
The following statements, for instance, create the DataInputStream stream input
and the DataOutputStream stream output to read and write primitive data values:
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 {
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");
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);
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.
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.
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();
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