Java TCP在客户端之间发送和接收多条消息;服务器端在同一个套接字上

时间:2014-03-15 06:18:30

标签: java sockets tcp

我有以下情况,

  1. TCP服务器将接受客户端连接
  2. 客户端将发送第一个请求,服务器将响应该请求,服务器必须在同一个套接字上等待接收来自同一客户端的下一个请求
  3. 请看我做的代码,这个代码服务器无法接收服务器发送的第二个请求,客户端也接收到第二个接收服务器的第一个响应。
  4. 请在此建议,代码中存在什么问题。
  5. 我尝试模拟这种情况,如果有人以前遇到过这种情况,请尽快提出建议。
  6. 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());
        }
    }}
    

    服务器端输出:

    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
    

    客户端输出:

    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>
    

2 个答案:

答案 0 :(得分:1)

您的客户端正在读取响应,直到流结束,这仅在对等方关闭套接字时发生,这使得无法进行多次交换。您需要设计另一种分隔消息的方法。在这种情况下,只需发送和接收线就足够了。

答案 1 :(得分:0)

在服务器上,您将PrintWriter设置为autoFlush(第二个参数)

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

并在写完后调用flush()。

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

然后客户正在阅读

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

它可能正在阅读第二次冲洗。在这种情况下,它没有任何东西可读,退出循环并打印先前的响应。打印后尝试清除客户端上的响应,并检查这是否是问题。