Introduction
TCP/IP sockets are the most reliable, bi-directional stream protocols. It is possible to send arbitrary amounts of data using TCP/IP. Sockets are used for data communication using this protocol. There are two kinds of sockets in Java, a server and a client. The ServerSocket class is used by the server to wait for the client, and the client connects to the server using the Socket class.
Socket Class
A Socket Object establishes connections between the client and server.
Constructors of Socket class
The first constructor takes the hostname and port as its parameter to create a Socket object. The creation of a Socket object throws an UnknownHostException or an IOException, which might be caught.
Socket s=new Socket (String hostname, int port);
The next constructor takes the InetAddress and port number as its parameters to create a Socket object. The constructor throws an IOException or an UnknownHostException, which must be caught and handled.
Socket s=new Socket(InetAddress a, int port);
Methods of Socket Class
- InetAddress getInetAddress(): Returns InetAddresses associated with Socket object.
- int getPort(): Returns the remote port to which this Socket object is connected.
- int getLocalPort(): Returns the local port to which the Socket object is connected.
- InputStream getInputStream: Returns the InputStream associated with this socket.
- OutputStream getOutputStream(): Returns the OutputStream associated with this socket.
- void close(): Closes both InputStream and OutputStream.
ServerSocket Class
The ServerSocket object waits for the client to make a connection. An object of this class registers itself as having an interest in client connection. Apart from using the methods listed above, this class uses the accept() method, which is used to wait for a client to initiate communications. The normal socket object is used for further data transfer.
Constructors of ServerSocket Class
There are two types of constructors available.
The first constructor accepts a port number as a parameter to create a server socket object on that port. The creation of this object throws an IOException, which must be caught and handled.
ServerSocket ss= new ServerSocket(int port);
The next constructor accepts a port with a maximum queue length as a parameter. The queue length indicates the maximum number of client connections that the system can have before refusing further connection.
ServerSocket ss=new ServerSocket (int port,int maxqu)
The following example has code for a server and client program. Use two instances of MS-DOS prompt and run the client program in one window and the server program in the other. Note that the client and the server program should run on the same machine. Run the FileServer before running the FileClient program. This program displays the contents of the file specified in the server to the client. Ensure that the specified file exists in the same directory as the server program.
Example
import java.net.*;
import java.io.*;
public class FClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
BufferedReader in = null;
try {
echoSocket = new Socket(InetAddress.getLocalHost(), 95);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
String userInput;
while ((userInput = in.readLine()) != null) {
System.out.println(userInput);
}
in.close();
echoSocket.close();
}
}
- Save the file FClient.java
- Compile the file using javac Fclient.java
- Run the file using Java Fclient
- Start the Notepad application and type the following line:
- Welcome to Socket Programming. I hope you enjoyed Mr. Ashish
- Save the file as soc.txt
Output
A new socket object is created using the local hostname and the port number. To read the input sent from the server, a BufferedReader object is created. The getInputStream of the Socket class is used to obtain the input stream from the server.
Open another file and type the following code.
import java.net.*;
import java.io.*;
public class FServer {
public static void main(String args[]) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(95);
} catch (IOException e) {
System.err.println("Could not listen on port: 95.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("Connected to: " + clientSocket);
} catch (IOException e) {
System.err.println("Accept Failed");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Data in Server");
String s = stdin.readLine();
File f = new File(s);
if (f.exists()) {
BufferedReader d = new BufferedReader(new FileReader(s));
String line;
while ((line = d.readLine()) != null) {
out.write(line);
out.flush();
}
d.close();
}
out.close();
clientSocket.close();
serverSocket.close();
}
}
- Save the file as FServer.java
- Open another instance of MS-DOS Prompt.
- Compile the file using javac fServer.java
- Run the file using Java FServer
Output
The ServerSocket object waits for a client to make the connection at port number 95. Once a client makes a connection, the accept method is called to accept the connection, after which a message is displayed giving details about the local port number, client address, and the port number of the client. The Server program requests for a file name. This file must be present in the current working directory. A check is made at the server end, and if the file exists, the data is read by the socket object using the getInputStream method. The transfer of data between the client program and the server program takes place using the socket object. The client end displays the file contents. Both the programs terminate after the request is serviced.
Summary
TCP/IP sockets provide a reliable, bi-directional communication protocol for transmitting arbitrary amounts of data. In Java, the Socket class is used to establish connections between a client and server, while the ServerSocket class enables the server to wait for client connections. The Socket object is created using a constructor that requires a hostname and port, potentially throwing UnknownHostException or IOException. These sockets facilitate efficient data communication and are essential for building client-server applications.