Java TCP send and receive multiple messages between client & server side on same socket

10,924

Solution 1

Your client is reading the response until end of stream, which only occurs when the peer closes the socket, which makes it impossible to have multiple exchanges. You need to devise another way to delimit messages. In this case, just sending and receiving lines would be sufficient.

Solution 2

On server you have PrintWriter set to autoFlush (second param)

outToClient = new PrintWriter(socket.getOutputStream(),true);

and also calling flush() after writing.

outToClient.print(strresponse); //autoFlush here
outToClient.flush();

then when client is reading

while((i = in.read()) > 0)

it is probably reading second flush. In that case, it has nothing to read, exits loop and prints previous response. Try to clear response on client after printing it and check if this was the problem.

Share:
10,924
Boobalan M
Author by

Boobalan M

Updated on June 05, 2022

Comments

  • Boobalan M
    Boobalan M almost 2 years

    I have the following situation,

    1. TCP server will accept the connection fron client
    2. Client wil send the first request and server will responds to that request and server must wait on the same socket to receive next request from the same client
    3. Please see the code that i did, With this code server not able to receive the second request send by server and client receiving the first response from server in 2nd receive also.
    4. Please suggest on this, what is problem in code.
    5. I try to simulate this case, if anyone met it previously, please kindly suggest on this soon.

    Client_MultipleMessages.java:

    public class Client_MultipleMessages {
        public static void main(String[] args) {
            Socket clientSocket = null;
            SocketAddress sockaddr = null;
            boolean IsSocketCreated = false;
            String p_Response = "";
            OutputStream outToServer = null;
            InputStream in = null;
            String strRequestString = "";
            try{
                clientSocket = new Socket();
                sockaddr = new InetSocketAddress("192.168.121.121", 1234);
                try{
                    clientSocket.connect(sockaddr, 1000);
                    if (clientSocket.isConnected()){
                        IsSocketCreated = true;
                    }
                }catch(Exception e){
                    System.out.println("Exception while creating socket,Reason is:"+ e.getMessage());
                }
                int index = 1;
                String req = "REGISTRATION_REQUEST";
                while(index <= 2){
                    if(clientSocket.isConnected()){
                        outToServer = clientSocket.getOutputStream();
                        System.out.println("Request "+index+":"+req);
                        outToServer.write(req.getBytes());
                        outToServer.flush();
                        //clientSocket.setSoTimeout(1000);
                        in = clientSocket.getInputStream();
                        int i = -1;
                        while((i = in.read()) > 0){
                            p_Response += (char) i;
                        }
                        System.out.println("Response "+index+":"+p_Response);
                    }
                    index++;
                    req = "LERGD_ALLOCATE_MSISDN";
                }   
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }
    

    Server_MultipleMessages.java

    public class Server_MultipleMessages {
        public static void main(String[] args) {
            try{
                ServerSocket Server = new ServerSocket (1234);
                while(true){
                    Socket socket = Server.accept();
                    String fromclient = "";
                    BufferedReader inFromClient = null;
                    PrintWriter outToClient = null;
                    String strresponse = "";
                    try{
                        int reqCount = 1;
                        socket.setSoTimeout(2000);
                        while(reqCount <= 2){
                            System.out.println("Request-"+reqCount);
                            inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            outToClient = new PrintWriter(socket.getOutputStream(),true);
                            char data[] = new char[1200];
                            inFromClient.read(data);
                            for (int i = 0; i < data.length; i++) {
                                fromclient = fromclient + Character.toString(data[i]);
                            }
                            System.out.println("XML Request is from client: "+fromclient+"\n\n");
                            String returnDesc = "success";
                            if(fromclient.contains("REGISTRATION_REQUEST")){
                                System.out.println("Request if for Registeration !!");
                                strresponse = "<REGISTRATION_RESPONSE><HEADER><ERROR_CODE>" + 0 + "</ERROR_CODE>              <ERROR_DESC>" + returnDesc + "</ERROR_DESC></HEADER><BODY>,DIAMETER-S6A,TCAP,</BODY></REGISTRATION_RESPONSE>";
                        }else if(fromclient.contains("LERGD_ALLOCATE_MSISDN")){
                            System.out.println("Request is for allocate Msisdnm !!");
                            strresponse = "<RESPONSE><HEADER><TRANSACTION_ID>123456</TRANSACTION_ID><REQUEST_TYPE>LERGD_ALLOCATE_MSISDN</REQUEST_TYPE><ERROR_CODE>" + 0 + "</ERROR_CODE><ERROR_DESC>" + returnDesc + "</ERROR_DESC></HEADER><BODY><ACTION_TAKEN>B</ACTION_TAKEN><ALLOCATED_MSISDN>7525600000</ALLOCATED_MSISDN></BODY></RESPONSE>";
                        }else{
                            System.out.println("Invalid Request from client !!");
                        }
                        System.out.println("XML Response to be send to client: "+strresponse+"\n\n");
                        outToClient.print(strresponse);
                        outToClient.flush();
                        strresponse = "";
                        fromclient = "";
                        reqCount++;
                    }
                }catch(Exception ex){
                    ex.printStackTrace();
                }finally{
                    if(!socket.isClosed()){
                        socket.close();
                    }
                }
            }
        }catch(Exception ex){
            System.out.println("Error in ProcessXmlRequest : "+ex.getMessage());
        }
    }}
    

    Server side output:

    Request-1
    XML Request is from client: REGISTRATION_REQUEST
    Request if for Registeration !!
    XML Response to be send to client: <REGISTRATION_RESPONSE><HEADER><ERROR_CODE>0</ERROR_CODE><ERROR_DESC>success</ERROR_DESC></HEADER><BODY>,DIAMETER-S6A,TCAP,</BODY></REGISTRATION_RESPONSE>
    Request-2
    java.net.SocketTimeoutException: Read timed out
    

    Client side output:

    Request 1:REGISTRATION_REQUEST
    Response 1:<REGISTRATION_RESPONSE><HEADER><ERROR_CODE>0</ERROR_CODE><ERROR_DESC>success</ERROR_DESC></HEADER><BODY>,DIAMETER-S6A,TCAP,</BODY></REGISTRATION_RESPONSE>
    Request 2:LERGD_ALLOCATE_MSISDN
    Response 2:<REGISTRATION_RESPONSE><HEADER><ERROR_CODE>0</ERROR_CODE><ERROR_DESC>success</ERROR_DESC></HEADER><BODY>,DIAMETER-S6A,TCAP,</BODY></REGISTRATION_RESPONSE>
    
  • Boobalan M
    Boobalan M about 10 years
    Can you please elaborate on this once?
  • user207421
    user207421 about 10 years
    Elaborate on what exactly? What part of it don't you understand?
  • Boobalan M
    Boobalan M about 10 years
    "Your client is reading the response until end of stream" - This point i am not getting clearly. As you said if client is reading end of steam then how client is sending second request to server?
  • user207421
    user207421 about 10 years
    Your client is looping until read() returns a zero or negative value. It can only return zero if the peer sends a zero byte, which it isn't, and it can only return a negative value if the peer closes the connection.
  • Boobalan M
    Boobalan M about 10 years
    If you mean the first response sent by server is not red by client fully, then your point is false because in output that i mentioned previously shows 1st request sent and response for the same received from serversuccessfully(Server did not closed the conn). The 2nd one also sent by client but server not receiving and client is receiving the previous response in second time also. Am i correct?
  • user207421
    user207421 about 10 years
    The client read loop can only exit for one of the two reasons I gave. Is this the real code? And if so can you tell us the value of 'i' when it exits?
  • Boobalan M
    Boobalan M about 10 years
    Yes that was the real code. Please see the i value in following output : Request 1:REGISTRATION_REQUEST value of i -1 Response 1:<REGISTRATION_RESPONSE><HEADER><ERROR_CODE>0</ERROR_CODE> <ERROR_DESC>success</ERROR_DESC></HEADER><BODY>,DIAMETER-S6A‌​,TCAP,</BODY></REGIS‌​TRATION_RESPONSE> Request 2:LERGD_ALLOCATE_MSISDN value of i -1 Response 2:<REGISTRATION_RESPONSE><HEADER><ERROR_CODE>0</ERROR_CODE> <ERROR_DESC>success</ERROR_DESC></HEADER><BODY>,DIAMETER-S6A‌​,TCAP,</BODY></REGIS‌​TRATION_RESPONSE>