简体   繁体   中英

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

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>

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM