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

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

本文介绍了Java TCP 在客户端和客户端之间发送和接收多条消息服务器端在同一个套接字上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况,

  1. TCP 服务器将接受来自客户端的连接
  2. 客户端将发送第一个请求,服务器将响应该请求,服务器必须在同一套接字上等待以接收来自同一客户端的下一个请求
  3. 请查看我所做的代码,使用此代码服务器无法接收服务器发送的第二个请求,而客户端在第二个接收中也接收来自服务器的第一个响应.
  4. 请就此提出建议,代码中有什么问题.
  5. 我尝试模拟这种情况,如果有人以前遇到过,请尽快提出建议.

Client_MultipleMessages.java:

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

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>

推荐答案

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

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

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

并在写入后调用flush().

and also calling flush() after writing.

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

然后当客户端正在阅读

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.

这篇关于Java TCP 在客户端和客户端之间发送和接收多条消息服务器端在同一个套接字上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 13:34