Reading from the socket

Now, let's check out an example where we will establish a connection to the server with the help of a socket. This will demonstrate how data can be sent and received between the client and the server. The following example is a server application making use of the Socket class to listen to clients on a port number specified by a command-line argument:

 

//Socket Server

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleSocketServer {
public static void main(String args[]) throws IOException {
// A new service registered with the 1286 port
ServerSocket ss = new ServerSocket(1286);
//Accept the connection request made with the server socket
Socket s=ss.accept();
// Establish the output stream from the socket connection
OutputStream socketOutStream = s.getOutputStream();
DataOutputStream socketDOS = new DataOutputStream
(socketOutStream);
// Communicate with the socket data stream with a message
socketDOS.writeUTF("Hello world!");
// Cleanup
socketDOS.close();
socketOutStream.close();
s.close();
ss.close();
}
}

In the preceding code, we have the SimpleSocketServer class when the main method constructor is invoked. This is where ServerSocket is instantiated with the given port. Further, when the thread starts, the serverSocket.accept() method is invoked and the server starts listening for requests on the given port. After that, when the client sends the request, the server responds and returns the response string to that call.

The following code is a SimpleSocketClient program that connects to SimpleSocketServer. Using the socket, send the test string and then wait for a response from the server that will contain the test string:

//Socket Client

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class SimpleSocketClient {
public static void main(String args[]) throws IOException {
// Establish a server connection through 1286 port
Socket s = new Socket("localhost",1286);
// Access the input stream of the server socket
InputStream sIn = s.getInputStream();
// Wrap the socket input stream with data input stream
DataInputStream socketDIS = new DataInputStream(sIn);
//Read from the socket data input stream
String testString= new String (socketDIS.readUTF());
//Print the data read
System.out.println(testString);
// clean up
socketDIS.close();
sIn.close();
s.close();
}
}

Using the SimpleSocketClient code, you can instantiate Socket() for a given server and port and also establish a connection. After that, the InputStream test string is read from the server socket.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset