0

I am writhing a java socket API that is able to send sting to my socket server and get back the response from server.

Below is my server code :

package com.test.socket;

import java.io.*;  
import java.net.*;
import java.util.Calendar;  
public class Server {  
    /**  Instantiates an instance of the SimpleServer class and initilaizes it.
     */
    public static void main(String[] args){
        Server simpleserver = new Server();
        simpleserver.init();
    }

    /**  Sets up a ServerSocket and listens on port 8189.
     */
    public void init(){
        ServerSocket serversocket = null;
        Socket socket = null;
        try{
            //establish a server socket monitoring port 8189 
            //port 8189 is not used by any services
            serversocket = new ServerSocket(8189);
            System.out.println("Listening at 127.0.0.1 on port 8189");

            //wait indefinitely until a client connects to the socket
            socket = serversocket.accept();

            //set up communications for sending and receiving lines of text data
            //establish a bufferedreaderr from the input stream provided by the socket object
            InputStreamReader inputstreamreader = new InputStreamReader(socket.getInputStream());
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            //establish an printwriter using the output streamof the socket object
            //and set auto flush on    
            PrintWriter printwriter = new PrintWriter(socket.getOutputStream(),true);

            //for binary data use
            // DataInputStream and DataOutputStream

            //for serialized objects use
            // ObjectInputStream and ObjectOutputStream

            String datetimestring = (Calendar.getInstance()).getTime().toString();
            printwriter.println("You connected to the Simple Server at " + datetimestring);

            String lineread = "";
            //        boolean done = false;
            while ((lineread = bufferedreader.readLine()) != null){
                System.out.println("Received from Client: " + lineread);
                printwriter.println(lineread);
                //          if (lineread.compareToIgnoreCase("Bye") == 0) done = true;
            }

        }catch(UnknownHostException unhe){
            System.out.println("UnknownHostException: " + unhe.getMessage());
        }catch(InterruptedIOException intioe){
            System.out.println("Timeout while attempting to establish socket connection.");
        }catch(IOException ioe){
            System.out.println("IOException: " + ioe.getMessage());
        }
    }
}  

Below is my socket client function,that makes a connection to the socket server and fetches the response :

public Integer socketClient(String server_ip_address,String strToBeSent){

    int serverport = 8189;
    Socket socket = null;
    InputStreamReader inputstreamreader = null;
    BufferedReader bufferedreader = null;
    PrintWriter printwriter = null;
    int result=ConfigurationManager.FAILED_CODE;
    try{
        System.out.println("Connecting to " + server_ip_address + " on port " + serverport);
        socket = new Socket(server_ip_address,serverport);
        //Set socket timeout for 10000 milliseconds or 10 seconds just 
        //in case the host can't be reached
        socket.setSoTimeout(10000);
        System.out.println("Connected.");

        inputstreamreader = new InputStreamReader(socket.getInputStream());
        bufferedreader = new BufferedReader(inputstreamreader);
        //establish an printwriter using the output streamof the socket object
        //and set auto flush on    
        printwriter = new PrintWriter(socket.getOutputStream(),true);
        printwriter.println(strToBeSent);
        String lineread = "";
        while ((lineread = bufferedreader.readLine()) != null){
            System.out.println("Received from Server: " + lineread);
        }
        result=ConfigurationManager.SUCCESS_CODE;

    }catch(UnknownHostException unhe){
        System.out.println("UnknownHostException: " + unhe.getMessage());
        result=ConfigurationManager.FAILED_CODE;
    }catch(InterruptedIOException intioe){
        System.out.println("Timeout after communication via socket connection. Server Terminated");
        System.out.println("Closing connection.");
        result=ConfigurationManager.SUCCESS_CODE;
        try {
            bufferedreader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            inputstreamreader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        printwriter.close();
    }
    catch(IOException ioe){
        System.out.println("IOException: " + ioe.getMessage());
        result=ConfigurationManager.FAILED_CODE;
    }finally{
        try{
            socket.close();
        }catch(IOException ioe){
            System.out.println("IOException: " + ioe.getMessage());
            result=ConfigurationManager.FAILED_CODE;
        }
    }
    return result;
}

Now everytime,I run the program,although my string is sent 2 odd things are happening 1) my server automatically gets terminated. So after sending the frst string when I make make another call to my socketclient function to send the second string it gives me error as the server was terminated. 2) when ever I make a socketclient method call,although the string was sent to server and I get the response back. but the program reaches the catch block catch(InterruptedIOException intioe){ System.out.println("Timeout after communication via socket connection. Server Terminated"); System.out.println("Closing connection.");

Instead of closing my socket normally.

Can I please have solution to this. How to resolve the server termination.

0 Answers0