0

一般来说,我是 Java 和 TCP 的新手。

我有以下场景,我向 tcp 服务器发送请求并直接收到回复,然后服务器稍后将发送未经请求的事件消息。

我实现了以下客户端

 import java.io.DataInputStream;
 import java.io.DataOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.net.Inet4Address;
 import java.net.InetAddress;
 import java.net.Socket;
 import java.net.SocketException;
 import java.net.UnknownHostException;

 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;

 public class TcpClient {

private InetAddress connectedAddress;
private Socket tcpSocket;
private int connectedPort;
private OutputStream outStream;
private boolean first = true;

private static final Log log = LogFactory.getLog(TcpClient.class);

public TcpClient(String host, int port) {
    try {
        this.connectedAddress = Inet4Address.getByName(host);
        this.connectedPort = port;
        this.tcpSocket = new Socket(connectedAddress, connectedPort);
        this.outStream = this.tcpSocket.getOutputStream();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void sendMessage(String message) throws IOException {
    log.debug("Sending Message \n" + message);
    synchronized (this) {
        if (!this.tcpSocket.isConnected())
            return;
        DataOutputStream dos = new DataOutputStream(outStream);
        dos.write(message.getBytes());
        dos.flush();
        if(first){
            first = false;
            (new Thread(new TcpListeningThread())).start();
        }
    }
}

private class TcpListeningThread implements Runnable {

    public TcpListeningThread() {
        // Nothing to do...
    }

    @Override
    public void run() {
        try {
            while (true) {
                DataInputStream dis = new   DataInputStream(tcpSocket.getInputStream());
                int len = dis.readInt();
                byte[] data = new byte[len];
                dis.read(data);
                String response = new String(data, "US-ASCII");
                if (null != response && !StringUtils.isBlank(response)) {
                log.debug("Received Response [" + response + "]");
                processXmlResponse(response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 }

}

此代码似乎仅读取发送的第一个请求的第一个响应,同时删除 if(first) 条件并在每次发送请求时调用读取线程,并删除 while true,代码似乎能够读取响应对于发送的每个请求,但当然无法读取事件消息。

我很感激任何帮助。

谢谢 :)

4

0 回答 0