java – 如何保持TCP套接字打开?

我们的应用程序与许多服务器进行乒乓式对话(每个服务器都有一个相应的线程,用于建立这些连接).下面的代码有效,但它为每个新请求打开一个新连接,并且只使用一次,很快就会达到服务器设置的最大连接上限.

DataProvider.java

public static ZnResult sendTcpQuery(String xml, String url, int port) {
    List<ZnXmlResult> results = new ArrayList<>();
    String xmlString = xml != null ? new String((xml + "\n").getBytes()) : "";
    int error = ZnResult.OK;
    try (Socket clientSocket = new Socket(url, port)) {
        clientSocket.setSoTimeout(CONNECTION_TIMEOUT);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        try (BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"))) {
            outToServer.writeBytes(xmlString);
            try (StringWriter responseFromServer = new StringWriter()) {
                String readLine;
                while ((readLine = inFromServer.readLine()) != null) {
                    ...
                }
            }
            outToServer.close();
            clientSocket.close();
        }
    } catch (Exception ex) {
        LOG.error("Exception {}", url + ":" + port, ex);
        error = ZnResult.ERR;
    }
    return error == ZnResult.OK ? new ZnResult(results) : new ZnResult(error);
}

我怎样才能改变它,所以一切都可以在一个连接中完成?
我想我会做这样的事情:

SocketFactory.java

public class SocketFactory {
private static HashMap<String, Socket> socketsByAddress = new HashMap<>();
private static HashMap<Socket, DataOutputStream> outputStreamsBySocket = new HashMap<>();
private static HashMap<Socket, BufferedReader> readersBySocket = new HashMap<>();

public static Socket getSocket(String address) {
    String ip = Tools.getIpFromAddress(address);
    int port = Tools.getPortFromAddress(address);
    Socket socket = socketsByAddress.get(address);
    if (socket == null) {
        try {
            socket = new Socket(ip, port);
            socket.setSoTimeout(60000);
            socketsByAddress.put(address, socket);
        } catch (IOException ex) {
            Logger.getLogger(SocketFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return socket;
}

public static DataOutputStream getOutputStream(Socket socket) {
    DataOutputStream outputStream = outputStreamsBySocket.get(socket);
    if (outputStream == null) {
        try {
            outputStream = new DataOutputStream(socket.getOutputStream());
            outputStreamsBySocket.put(socket, outputStream);
        } catch (IOException ex) {
            Logger.getLogger(SocketFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return outputStream;
}

public static BufferedReader getReader(Socket socket) {
    BufferedReader reader = readersBySocket.get(socket);
    if (reader == null) {
        try {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            readersBySocket.put(socket, reader);
        } catch (IOException ex) {
            Logger.getLogger(SocketFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return reader;
}
}

DataProvider.java

public static ZnResult sendTcpQuery(String xml, String url, int port) {
    List<ZnXmlResult> results = new ArrayList<>();
    int error = ZnResult.OK;
    try {
        String xmlString = xml != null ? new String((xml + "\n").getBytes()) : "";
        Socket clientSocket = SocketFactory.getSocket(url + ":" + port);
        DataOutputStream outToServer = SocketFactory.getOutputStream(clientSocket);
        BufferedReader inFromServer = SocketFactory.getReader(clientSocket);
        outToServer.writeBytes(xmlString);
        try (StringWriter responseFromServer = new StringWriter()) {
            String readLine;
            while ((readLine = inFromServer.readLine()) != null) {
                ...
            }
        }
    } catch (Exception ex) {
        LOG.error("Exception {}", url + ":" + port, ex);
        error = ZnResult.ERR;
    }
    return error == ZnResult.OK ? new ZnResult(results) : new ZnResult(error);
}

但它只是不起作用,只有第一个通过.

最佳答案 此循环读取直到流结束.

while ((readLine = inFromServer.readLine()) != null) {

流只会结束一次.即你不能结束流但后来再次使用它.

你需要做什么呢

>有一条终止线,在您的数据中不会出现.例如等待“[EOF]”
>首先发送数据长度,只读取那么多数据.

点赞