Docsity

Socket Programming: Client-Server Communication using Java, Lecture notes of Web Design and Development

Partial preview of the text

Download Socket Programming: Client-Server Communication using Java and more Lecture notes Web Design and Development in PDF only on Docsity!

HANDOUTS

WEB DESIGN AND DEVELOPMENT

Lecture 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

ƒ 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

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) ;

ƒ serverName : Name or address of the server you wanted to connect such

as 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);

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();

// step 5: Send / Receive message //String reading name name = br.readLine(); sent by client //String appending msg = “hello”"Hello "with + name the +received " from Server";name // sending back to client pw.println(msg); //s.close(); closing communication sockey } // 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 importimport java.net.;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 then you can pass “localhost” as server address / / Noticewhile creatingthat port server no is socketsimilar */ to one passed 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); OutputStreamPrintWriter pwos == news.getOutputStream(); PrintWriter(os,true);

// step 4: Send / Receive message // asking use to enter his/her name String msg = JOptionPane.showInputDialog( "Enter your name"); // pw.println(msg); sending name to server

//// readingserver message (name appended with hello) from msg = br.readLine();

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

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 ☺