ZeePedia

JAVA: Socket Programming

<< JAVA Applets
JAVA: Serialization >>
img
Web Design & Development ­ CS506
VU
Lesson 21
Socket Programming
Socket
A socket is one endpoint of a two-way communication link between two programs running
generally on a network.
A socket is a bi-directional communication channel between hosts. A computer on a network often
termed as host.
Socket Dynamics
As you have already worked with files, you know that file is an abstraction of your hard drive.
Similarly you can think of a socket as an abstraction of the network.
Each end has input stream (to send data) and output stream (to receive data) wired up to the other
host.
You store and retrieve data through files from hard drive, without knowing the actual dynamics of
the hard drive. Similarly you send and receive data to and from network through socket, without
actually going into underlying mechanics.
You read and write data from/to a file using streams. To read and write data to socket, you will also
use streams.
What is Port?
It is a transport address to which processes can listen for connections request.
There are different protocols available to communicate such as TCP and UDP. We will use TCP
for programming in this handout.
There are 64k ports available for TCP sockets and 64k ports available for UDP, so at least
theoretically we can open 128k simultaneous connections.
There are well-known ports which are
o
below 1024
o
provides standard services
o
Some well-known ports are:
-FTP works on port 21
-HTTP works on port 80 -TELNET works on port 23 etc.
How Client ­ Server Communicate
Normally, a server runs on a specific computer and has a socket that is bound to a specific port
number.
The server just waits, listening to the socket for a client to make a connection request.
On the client side: The client knows the hostname of the machine on which the server is running
and the port number to which the server is connected.
On the server side, if the connection is accepted, a socket is successfully created and the client can
use the socket to communicate with the server.
Note that the socket on the client side is not bound to the port number used to make contact with
the server. Rather, the client is assigned a port number local to the machine on which the client is
running.
The client and server can now communicate by writing to or reading from their sockets
157
img
Web Design & Development ­ CS506
VU
. As soon as client creates a socket that socket attempts to connect to the specified server.
. The server listens through a special kind of socket, which is named as server socket.
. The sole purpose of the server socket is to listen for incoming request; it is not used for
communication.
. If every thing goes well, the server accepts the connection. Upon acceptance, the server gets a new
socket, a communication socket, bound to a different port number.
. The server needs a new socket (and consequently a different port number) so that it can continue to
listen through the original server socket for connection requests while tending to the needs of the
connected client. This scheme is helpful when two or more clients try to connect to a server
simultaneously (a very common scenario).
Steps ­ To Make a Simple Client
To make a client, process can be split into 5 steps. These are:
1. Import required package
You have to import two packages
. java.net.*;
. java.io.*;
2. Connect / Open a Socket with Server
Create a client socket (communication socket)
Socket s = new Socket("serverName", serverPort) ;
Name or address of the server you wanted to connect such as
serverName :
http://www.google.com or 172.2.4.98 etc. For testing if you are
running client and server on the same machine then you can
specify "localhost" as the name of server
. serverPort :
Port number you want to connect to
The scheme is very similar to our home address and then phone number.
3. Get I/O Streams of Socket
Get input & output streams connected to your socket
.  For reading data from socket As stated above, a socket has input stream attached to it.
InputStream is = s.getInputStream();
// now to convert byte oriented stream into character oriented buffered reader // we use intermediary
stream that helps in achieving above stated purpose
InputStreamReader isr= new InputStreamReader(is); BufferedReader br = new BufferedReader(isr);
.  For writing data to socket
A socket has also output stream attached to it. Therefore,
OutputStream os = s.getOutputStream();
// now to convert byte oriented stream into character oriented print writer
// here we will not use any intermediary stream because PrintWriter constructor // directly accepts
an object of OutputStream
PrintWriter pw = new PrintWriter(os, true);
158
img
Web Design & Development ­ CS506
VU
Here notice that true is also passed to so that output buffer will flush.
4. Send / Receive Message
Once you have the streams, sending or receiving messages isn't a big task. It's very much similar to the
way you did with files
.  To send messages
pw.println("hello world");
.  To read messages
String recMsg = br.readLine();
5. Close Socket
Don't forget to close the socket, when you finished your work
s.close();
Steps ­ To Make a Simple Server
To make a server, process can be split into 7 steps. Most of these are similar to steps used in making a
client. These are:
1. Import required package
You need the similar set of packages you have used in making of client
. java.net.*;
. java.io.*;
2. Create a Server Socket
In order to create a server socket, you will need to specify port no eventually on which server will listen
for client requests.
ServerSocket ss = new ServerSocket(serverPort) ;
. serverPort: port local to the server i.e. a free port on the server machine. This
is the same port number that is given in the client socket constructor
3. Wait for Incoming Connections
The job of the server socket is to listen for the incoming connections. This listening part is done
through the accept method.
Socket s = ss.accept();
The server program blocks ( stops ) at the accept method and waits for the incoming client connection
when a request for connection comes it opens a new communication socket (s) and use this socket to
communicate with the client.
4. Get I/O Streams of Socket
Once you have the communication socket, getting I/O streams from communication socket is similar to
the way did in making a client
1. For reading data from socket
InputStream is = s.getInputStream(); InputStreamReader isr= new
InputStreamReader(is); BufferedReader br = new BufferedReader(isr);
2. For writing data to socket
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
5. Send / Receive Message
Sending and receiving messages is very similar as discussed in making of client
To send messages:
pw.println("hello world");
. To read messages
String recMsg = br.readLine();
6. Close Socket
s.close();
Example Code 21.1: Echo Server & Echo Client
The client will send its name to the server and server will append "hello" with the name send by the client.
After that, server will send back the name with appended "hello".
EchoServer.java
159
img
Web Design & Development ­ CS506
VU
Let's first see the code for the server
// step 1: importing required package
import java.net.*;
import java.io.*;
import javax.swing.*;
public class EchoServer
{
public static void main(String args[])
{
try
{
//step 2: create a server socket
ServerSocket ss = new ServerSocket(2222);
System.out.println("Server started...");
/* Loop back to the accept method of the serversocket and wait for a new connection request.
Soserver will continuously listen for requests
*/
while(true) {
// step 3: wait for incoming connection
Socket s = ss.accept();
System.out.println("connection request recieved");
// step 4: Get I/O streams
InputStream is = s.getInputStream();InputStreamReader isr= new
InputStreamReader(is);BufferedReader br = new BufferedReader(isr);
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os,true);
// step 5: Send / Receive message
// reading name sent by clientString name = br.readLine(); // appending "hello" with the
received name
String msg = "Hello " + name + " from Server"; // sending back to client
pw.println(msg);
// closing communication sockeys.close();
} // end while
}catch(Exception ex){
System.out.println(ex); } } } // end class
EchoClient.java
The code of the client is given below
// step 1: importing required package
import java.net.*;import java.io.*;import
javax.swing.*;
public class EchoClient{
public static void main(String args[]){
try {
//step 2: create a communication socket
// if your server will run on the same machine thenyou can pass "localhost" as server address */
/* Notice that port no is similar to one passedwhile creating server socket */server
Socket s = new Socket("localhost", 2222);
// step 3: Get I/O streams
InputStream is = s.getInputStream();InputStreamReader isr= new
InputStreamReader(is);BufferedReader br = new BufferedReader(isr);
OutputStream os = s.getOutputStream();PrintWriter pw = new
160
img
Web Design & Development ­ CS506
VU
PrintWriter(os,true);
// step 4: Send / Receive message
// asking use to enter his/her name
String msg = JOptionPane.showInputDialog("Enter your name");
// sending name to server
pw.println(msg);
// reading message (name appended with hello) from// servermsg = br.readLine();
// displaying received messageJOptionPane.showMessageDialog(null , msg);
// closing communication sockets.close();
}catch(Exception ex){ System.out.println(ex); } } }
// end class
Compile & Execute
After compiling both files, run EchoServer.java first, from the command prompt window. You'll see a
message of "server started" as shown in the figure below. Also notice that cursor is continuously blinking
since server is waiting for client request
Now, open another command prompt window and run EchoClient.java from it. Look at EchoServer
window; you'll see the message of "request received". Sooner, the EchoClient program will ask you to
enter name in input dialog box. After entering name press ok button, with in no time, a message dialog box
will pop up containing your name with appended "hello" from server. This whole process is illustrated
below in pictorial form:
sending name to server
response from server
161
img
Web Design & Development ­ CS506
VU
Notice that server is still running, you can run again EchoClient.java as many times untill server is running.
To have more fun, run the server on a different computer and client on a different. But before doing that
find the IP of the computer machine on which your EchoServer will eventually run. Replace "localhost"
with the new IP and start conversion over network
References
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This
material is available just for the use of VU students of the course Web Design and Development and not for
any other commercial purpose without the consent of author.
162