Socket Programing
Socket Programing
Socket Programing
Socket Programming
This chapter presents key concepts of intercommunication between programs running on different computers
in the network. It introduces elements of network programming and concepts involved in creating network
applications using sockets. The chapter introduces the java.net package containing various classes re-
quired for creating sockets and message communication using two different protocols. It provides several
example programs demonstrating various capabilities supported by Java for creating network applications.
O Aer learning the contents of this chapter, the reader will be able to:
B Chapter
∑ understand fundamental concepts of computer communication
J ∑ understand sockets and ports
E ∑ understand java.net package features
∑ program Java Sockets
C
T
I
∑ create comprehensive network applications using sockets
13
V
E
S
13.1 INTRODUCTION
Internet and WWW have emerged as global ubiquitous media for communication and changed the way
we conduct science, engineering, and commerce. They are also changing the way we learn, live, enjoy,
communicate, interact, engage, etc. The modern life activities are getting completely centered around or
driven by the Internet.
To take advantage of opportunities presented by the Internet, businesses are continuously seeking new
and innovative ways and means for offering their services via the Internet. This created a huge demand
for software designers and engineers with skills in creating new Internet-enabled applications or porting
existing/legacy applications to the Internet platform. The key elements for developing Internet-enabled
applications are a good understanding of the issues involved in implementing distributed applications and
sound knowledge of the fundamental network programming models.
Socket Programming 347
13.1.1 Client/Server Communication
At a basic level, network-based systems consist of a server, client, and a media for communication
as shown in Fig. 13.1. A computer running a program that makes a request for services is called client
machine. A computer running a program that offers (cung cấp) requested services from one or more clients
is called server machine. The media for communication can be wired or wireless network (Phương tiện
truyền thông có thể là mạng có dây hoặc mạng không dây) .
Fig. 13.4 Establishment of path for two-way communication between a client and server
The Interfaces
∑ ContentHandlerFactory
∑ FileNameMap
∑ SocketImplFactory
∑ URLStreamHandlerFactory
350 Object-Oriented Programming with Java
Exceptions
∑ BindException
∑ ConnectException
∑ MalformedURLException
∑ NoRouteToHostException
∑ ProtocolException
∑ SocketException
∑ UnknownHostException
∑ UnknownServiceException
A simple Server Program in Java The steps for creating a simple server program are:
1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
Socket Programming 351
Program 13.1
// SimpleServer.java: A simple server program.
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1254
ServerSocket s = new ServerSocket(1254);
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF(“Hi there”);
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}
A simple Client Program in Java The steps for creating a simple client program are:
1. Create a Socket Object:
Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);
4. Close the socket when done:
client.close();
An example program illustrating establishment of connection to a server and then reading a message
sent by the server and displaying it on the console is given below:
352 Object-Oriented Programming with Java
Program 13.2
// SimpleClient.java: A simple client program.
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1254
Socket s1 = new Socket(“localhost”,1254);
// Get an input file handle from the socket and read the input
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());
System.out.println(st);
// When done, just close the connection and exit
dis.close();
s1In.close();
s1.close();
}
}
Running Socket Programs Compile both server and client programs and then deploy server program
code on a machine which is going to act as a server and client program, which is going to act as a client.
If required, both client and server programs can run on the same machine. To illustrate execution of server
and client programs, let us assume that a machine called mundroo.csse.unimelb.edu.au on which we
want to run a server program as indicated below:
[raj@mundroo] java SimpleServer
The client program can run on any computer in the network (LAN, WAN, or Internet) as long as there
is no firewall between them that blocks communication. Let us say we want to run our client program on a
machine called gridbus.csse.unimelb.edu.au as follows:
[raj@gridbus] java SimpleClient
The client program is just establishing a connection with the server and then waits for a message. On
receiving a response message, it prints the same to the console. The output in this case is:
Hi there
which is sent by the server program in response to a client connection request.
It should be noted that once the server program execution is started, it is not possible for any other server
program to run on the same port until the first program which is successful using it is terminated. Port
numbers are a mutually exclusive resource. They cannot be shared among different processes at the same
time.
do not come without performance costs, it would be better to use a lighter transport protocol. This kind of
service is accomplished by the UDP protocol which conveys datagram packets.
Datagram packets are used to implement a connectionless packet delivery service supported by the UDP
protocol. Each message is transferred from source machine to destination based on information contained
within that packet. That means, each packet needs to have destination address and each packet might be
routed differently, and might arrive in any order. Packet delivery is not guaranteed.
The format of datagram packet is:
Program 13.3
// UDPServer.java: A simple UDP server program.
import java.net.*;
import java.io.*;
public class UDPServer {
354 Object-Oriented Programming with Java
Program 13.4
// UDPClient.java: A simple UDP client program.
import java.net.*;
import java.io.*;
public class UDPClient {
}
try {
aSocket = new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = Integer.valueOf(args[2]).intValue();
DatagramPacket request =
new DatagramPacket(m, args[0].length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println(“Reply: ” + new String(reply.getData()));
}
catch (SocketException e) {
System.out.println(“Socket: ” + e.getMessage());
}
catch (IOException e) {
System.out.println(“IO: ” + e.getMessage());
}
finally {
if (aSocket != null)
aSocket.close();
}
}
}
Program 13.5
// MathService.java: A basic math interface.
public interface MathService {
public double add(double firstValue, double secondValue);
public double sub(double firstValue, double secondValue);
public double div(double firstValue, double secondValue);
public double mul(double firstValue, double secondValue);
}
The implementation of this interface is not related to any network operation. The following code shows
a very simple implementation of this interface:
Program 13.6
// PlainMathService.java: An implementation of the MathService interface.
public class PlainMathService implements MathService {
The implementation of the MathServer is quite straightforward, which looks pretty similar to the echo
server mentioned previously. The difference is that the MathServer have to consider the specific protocol
defined by the math server and client communication. The program uses a very simple protocol operator:
first_value:second_value. It is the math server’s responsibility to understand this protocol and delegate to
the proper methods such as add, sub, mul, or div.
Program 13.7
// MathServer.java : An implementation of the MathServer.
import java.io.*;
import java.net.*;
A test client program that can access the math server is shown below:
Program 13.8
// MathClient.java: A test client program to access MathServer.
import java.io.*;
import java.net.Socket;
public class MathClient {
public static void main(String [] args){
String hostname = “localhost”;
int port = 10000;
if (args.length != 2) {
System.out.println(“Use the default setting...”);
}
else {
Socket Programming 359
hostname = args[0];
port = Integer.parseInt(args[1]);
}
try {
// create a socket
Socket socket = new Socket(hostname, port);
// perform a simple math operation “12+21”
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
writer.write(“+:12:21”);
writer.newLine();
writer.flush();
// get the result from the server
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
System.out.println(reader.readLine());
reader.close();
writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Program 13.9
// QueryStringFormatter.java: encodes a string with non-ASCII characters.
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
Program 13.10
// TextBasedSearchEngine.java:
import java.io.*;
import java.net.*;
13.7
Developing network applications is made possible in Java by using sockets, threads, RMI,
clustering, and Web services. These technologies allow for the creation of portable, efficient, and
maintainable large and complex Internet applications. The java.net package provides a powerful
and flexible set of classes for implementing network applications.
Typically, programs running on client machines make requests to programs on a server
machine. These involve networking services provided by the transport layer. The most widely
used transport protocols on the Internet are TCP (Transmission control Protocol) and UDP
(User Datagram Protocol). TCP is a connection-oriented protocol providing a reliable flow of data
between two computers. It is used by applications such as the World Wide Web, e-mail, p, and
secure shell. On the other hand, UDP is a simpler message-based connectionless protocol which
sends packets of data known as datagrams from one computer to another with no guarantees of
arrival. Network applications using UDP include Domain Name Systems (DNS), streaming
media applications as IPTV, VoIP, and online games. Both protocols use ports for application-
to-application communication. A port is a logical access point represented by a positive 16-bit
integer value. Each service offered by a computer is uniquely identified by a port number. Each
Internet packet contains both destination IP address and the port to which the request is to be
delivered. Some ports are reserved for common services such as p, telnet, smtp, hp, hps, and
login. Port numbers >=1024 are generally used for user-level services.
Sockets provide an interface for programming networks at the transport layer. Using sockets,
network communication is very much similar to performing file I/O. A socket is an endpoint
of a two-way communication link between two programs running on the network. The source
and destination IP address, and the port numbers constitute a network socket. Two key classes
from java.net package used in creation of server and client programs are ServerSocket,
which represents a server socket, and Socket, an instantiation of which performs the
actual communication with the client. Datagram communication is also supported through
DatagramPacket and DatagramSocket classes. Writing and reading data between server and
the client is also supported through the URLconnection class.
13.8 EXERCISES
Objective Questions
13.1 ______ is a connection-oriented and reliable protocol, ______ is a less reliable protocol.
13.2 The TCP and UDP protocols use ______ to map incoming data to a particular process running on a
computer.
13.3 Datagrams are normally sent by ______ protocol.
13.4 Java uses ______ class representing a server and ______ class representing the client that uses TCP
protocol.
13.5 ______ is used to wait for accepting client connection requests.
13.6 Class ______ is used to create a packet of data for UDP protocol.
13.7 If something goes wrong related to the network, ______ will be thrown when dealing with TCP/
UDP programming in Java.
13.8 The main purpose of URL encoding is to maintain the ______ between various platforms.
13.9 Based on the URL encoding mechanism, “www.test.com/test me&test you” becomes ______.
Socket Programming 363
Review Questions
Programming Problems
13.27 Write a simple program that can read a host name and convert it to an IP address.
13.28 Write a URL-based program that pulls content from www.buyya.com.
13.29 Write a ping-pong client and server application. When a client sends a ping message to the server,
the server will respond with a pong message. Other messages sent by the client can be safely
dropped by the server.
13.30 Rewrite the math server application, instead of using the TCP socket, use the UDP datagram
socket.
13.31 Write an online dictionary application, users are able to search online dictionary and get the
meaning of the words. The online dictionary should maintain its indexing in order to enhance the
performance and scalability.
13.32 Write a simple crawler program that can parse certain HTML information and find out the
hyperlinks within the HTML. (Use the URLConnection class to implement this application).
13.33 Write a Socket-based Java server program that responds to client messages as follows: When it
receives a message from a client, it simply converts the message into all uppercase letters and sends
back the same to the client. Write both client and server programs demonstrating this.