20 Java Socket Programming

Dr M. Vijayalakshmi

TCP and UDP

 

There are two types of Internet Protocols (IP) called TCP or Transmission Control Protocol and UDP or User Datagram Protocol. TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers whereas UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another without guarantee about arrival. Hence, UDP is not connection-based like TCP.

 

TCP is suited for applications that require high reliability, and transmission time is relatively less critical. UDP is suitable for applications that need fast, efficient transmission, such as games. UDP’s stateless nature is also useful for servers that answer small queries from huge numbers of clients.

   TCP/IP Server/Client Sockets

 

TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between hosts on the Internet. A socket can be used to connect Java’s I/O system to other programs that may reside either on the local machine or on any other machine on the Internet.

 

Kinds of TCP Sockets

 

There are Two kinds of TCP sockets in Java. One is for servers, and the other is for clients.

  1. The ServerSocket class is designed to be a “listener,” which waits for clients to connect before doing anything. Hence, ServerSocket is for servers.
  2. The Socket class is designed to connect to server sockets and to initiate protocol exchanges. The Socket class is for clients. The creation of a Socket object implicitly establishes a connection between the client and server.

     Create Client Sockets

 

There are two constructors used to create client sockets as shown in Table 22.1.

 

 

Instance Methods for Sockets

 

Socket defines several instance methods as shown in Table 22.2.

 

 

Input and Output Stream

 

The input and output streams associated with a Socket constructor by the use of the getInputStream( ) and getOuptutStream( ) methods are shown in Table 22.3.

 

 

Sockets

 

java.net.Socket is an abstraction of a bi-directional communication channel between hosts.

 

 

Through sockets, data can be sent and received via Input stream and Output Stream of sockets as shown in Figure 22.1.

    Socket Communication

 

A server (program) runs on a specific computer and has a socket that is bound to a specific port.The server waits and listens to the socket for a client to make a connection request. This is shown in Figure 22.1.

 

     Implementing Server

 

The steps involved in implementing Server socket communication is shown below.

 

1. Open the Server Socket

 

ServerSocket server;

DataOutputStream os;

DataInputStream is;

server = new ServerSocket(PORT);

 

2.  Wait for the Client Request

 

Socket client = server. accept();

 

3. Create I/O streams for communicating to the client

 

is = new DataInputStream(client.getInputStream());

os = new DataOutputStream(client.getOutputStream());

 

4. Perform communication with client

 

Receive from client:

String line = is.readLine();

Send to client:

os.writeBytes(“Hello\n”);

 

5. Close sockets

 

client.close();

 

Implementing Client

 

The steps involved in implementing Client socket communication is shown below.

 

1. Create a Socket Object:

 

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

 

Client/Server Communication

 

The server must be running when a client starts. the Client/Server communication with sockets is explained pictorialy in Figure 22.4.

 

The Server creates a server socket, bind to a port and waits for client connections. The Client requests for a connection and when the connection is accepted by the server, a socket is created. Then communication takes place using Input Output streams through sockets.

 

Data Transmission Through Sockets

 

Figure 22.5 illustrates the code used to create sockets and to establish connection between server and client. Once the connection request is accepted, data transmission takes place via streams through sockets between the client and the server.

 

The methods used for creating Input and Ouput streams are given below.

 

InputStream input = socket.getInputStream();

OutputStream output = socket.getOutputStream

   

A Simple Server Code

 

//  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 1234

//  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 server code is given above. A server socket is created and registered its service on port 1234. The server then listens for clients connection and accept it. Once connection is established, the server gets a communication stream associated with the socket and sends a string to the client. Finally it closes the connection.

 

A Simple Client Code

 

//  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 1234 Socket s1 = new Socket(“vijim.ist.au”,1234);

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

}

}

 A simple client code is given above. The client requests for a connection at port 1234 registered by the server. Once connection is accepted a socket is created. The client then gets an input stream associated with the socket and reads the string sent by the server. When this is done, it closes the connection.

 

Example of Server

 

A working example of Server and Client is given here.Both the server and the client are running in the local host.

A simple server code is given below. A server socket is created and registered its service on port 6014. The server then waits for clients connection and accept it. Once connection is established, the server gets an input stream associated with the socket represented as fromsock to read a string from the client. The string is then displayed on the server screen. Again the server gets an output stream represented as toSock to write an ‘OK’ message to the client. Finally it closes the connection.

   import java.io.*;

import java.net.*;

class Server2

{

public static void main(String args[])

{

ServerSocket Server;

Socket s;

BufferedReader fromKbd,fromSock;

PrintStream toSock;

String line;     int i ;

try

{

Server = new ServerSocket(6014);

System.out.println(“Waiting”);

s = Server.accept();

System.out.println(“Connection accepted”);

fromSock = new BufferedReader( new InputStreamReader(s.getInputStream()));

line = fromSock.readLine();

System.out.println(line);

toSock = new PrintStream(s.getOutputStream()); toSock.println(“Ok”);

Server.close();

s.close();

}

catch(Exce ption e)

{

System.out.println(“Exception”+e);

}

}

}

    Example of Client

 

A simple client code is given here. The client requests for a connection at port 6014 registered by the server in the local host. Once connection is accepted a socket is created. The client reads a string from the user using a Buffered stream represented as fromKbd. The client then gets an output stream associated with the socket toSock to write a string to the server. Again the client gets an input stream associated with the socket fromSock to read the message sent by the server. When this is done, it closes the connection.

 

import java.io.*;

import java.net.*;

class Client2

{

public static void main(String a[])

{

Socket s;

BufferedReader fromKbd;

PrintStream toSock;

BufferedReader fromSock;

String line;

try

{

s = new Socket(InetAddress.getByName(“localhost”),6014);

fromKbd = new BufferedReader( new InputStreamReader(System.in)); System.out.println(“Enter a String”); line = fromKbd.readLine();

toSock = new PrintStream(s.getOutputStream()); toSock.println(line);

fromSock = new BufferedReader( new InputStreamReader(s.getInputStream()));

line = fromSock.readLine();

System.out.println(line);

s.close();

}

catch(Exception e)

{ }

}

}

 

Output of Client & Server

 

The output of the above example program is shown in FIgure 22.6.

 

     Example of Chat TCP Server

 

This example is to illustrate about chat server and chat client using TCP sockets.A server socket is created and registered its service on port 6014. The server then waits for client connection and accept it. Once connection is established, the server gets a Buffered stream fromKbd to read strings from the keyboard. The server then gets an output stream represented as toSock to write an strings to the client. This runs in a loop and finally it closes the connection.

 

import java.io.*;

import java.net.*;

class TCPServerChat

{

public static void main(String args[])

{

ServerSocket Server;

Socket s;

BufferedReader fromKbd,fromSock;

PrintWriter out; String line;

try

{

Server = new ServerSocket(6014);

System.out.println(“Waiting”);

s = Server.accept();

System.out.println(“Connection accepted”);

out = new PrintWriter(s.getOutputStream(), true);

fromSock = new BufferedReader(new InputStreamReader(s.getInputStream()));

fromKbd = new BufferedReader(new InputStreamReader(System.in));

System.out.println(“I am ready now”);

while((line = fromKbd.readLine()) != null)

{

out.println(line);

}

}

catch(Exception e)

{

System.out.println(“Exception”+e);

}

}

}

 

Example of Chat TCP Client

 

The client requests for a connection at port 6014 registered by the server in the local host. Once connection is accepted a socket is created. The client reads strings from the user using a Buffered stream represented as fromKbd. The client then gets an output stream associated with the socket toSock to write strings to the server. This runs in a loop and and it closes the connection when done.

 

import java.io.*;

import java.net.*;

class TCPClientChat

{

public static void main(String a[])

{

Socket s;

BufferedReader fromKbd, fromSock;

PrintWriter out;

String line;

try

{

s = new Socket(InetAddress.getLocalHost(),6014);

out = new PrintWriter(s.getOutputStream(), true);

fromSock=newBufferedReader(new InputStreamReader(s.getInputStream()));

fromKbd=newBufferedReader(new InputStreamReader(System.in));

System.out.println(“I am ready now”);

while((line = fromKbd.readLine()) != null)

{

out.println(line);

}

}

catch(Exception e)

{

System.out.println(“Exception”+e);

}

}

}

Output of TCP Chat

 

The output of Chat server and Chat client using TCP sockets is shown in Figure 22.7 and Figure 22.8.

 

 

Example of FTP TCP Server

 

This is another example for file transfer from server to client using TCP sockets.

 

A simple server code is given below. A server socket is created and registered its service on port 6014. The server then waits for clients connection and accept it. Once connection is established, the server gets an input stream associated with the socket represented as fromsock to read the filename requested by the client. The filename is then displayed on the server screen. The server then gets an file input stream represented as fromFile to read from the file line by line. It then writes to the socket using an output stream toSock to the client. Finally it closes the connection.

 

import java.io.*;

import java.net.*;

class FTPTCPServer

{

public static void main(String args[])

{

ServerSocket ftpServer;

Socket s4ftp;

BufferedReader fromFile,fromKbd,fromSock;

FileInputStream fis;

PrintStream toSock;

String fileName,line;

try

{

ftpServer = new ServerSocket(6014);

System.out.println(“Waiting”);

s4ftp = ftpServer.accept();

System.out.println(“Connection accepted”);

fromSock = new BufferedReader(new InputStreamReader(s4ftp.getInputStream()));

fileName = fromSock.readLine();

System.out.println(fileName);

fis = new FileInputStream(fileName);

//System.out.println(fileName);

fromFile = new BufferedReader( new InputStreamReader(fis)); toSock = new PrintStream(s4ftp.getOutputStream()); while( (line=fromFile.readLine()) != null )

{

//System.out.println(fileName);

toSock.println(line);

System.out.println(line);

}

toSock.println(“EOF”);

ftpServer.close();

fis.close();

s4ftp.close();

}

catch(Exception e)

{

System.out.println(“Exception”+e);

}

}

}

 

Example of FTP TCP Client

 

A simple client code is given here. The client requests for a connection at port 6014 registered by the server in the local host. Once connection is accepted a socket is created. The client reads the filename requested by the user using a Buffered stream represented as fromKbd. The client then gets an output stream associated with the socket toSock to send the filename to the server. Again the client gets an input stream associated with the socket fromSock to read the file content sent by the server and write it to a file using an file ouput stream toFile. It also displays in the client screen. When this is done, it closes the connection.

 

import java.io.*;

import java.net.*;

class FTPTCPClient

{

public static void main(String a[])

{

Socket s4file;

FileOutputStream fos;

BufferedReader fromKbd,fromSock;

PrintStream toSock,toFile;

String fileName,line;

try

{

s4file = new Socket(InetAddress.getByName(“localhost”),6014); fromKbd = new BufferedReader( new InputStreamReader(System.in)); System.out.println(“Enter filename”); fileName = fromKbd.readLine();

toSock = new PrintStream(s4file.getOutputStream()); toSock.println(fileName);

fromSock = new BufferedReader( new InputStreamReader(s4file.getInputStream()));

fos = new FileOutputStream(“copy.txt”);

toFile = new PrintStream(fos);

while( !(line=fromSock.readLine()).equals(“EOF”) )

{

toFile.println(line);

System.out.println(line );

}

fos.close();

s4file.close();

}

catch(Exception e)

{

}

}

}

    Output of FTP TCP server & Client

 

The output of FTP server and FTP client using TCP sockets is shown in Figure 22.9.

 

Summary

 

This module have discussed about the basics of Socket Programming and also discussed about the client server communication with Socket programming. Moreover, this module has explored about Socket and ServerSocket classes in Java and to build TCP communication between two hosts.

 

 

References

  1. Herbert Schildt, Java: The Complete Reference, 7th Edition, McGraw-Hill, 2010.
  2. www.diffen.com/difference/TCP_vs_UDP