TCP连接线程,用于在java中读写和接收事件消息

时间:2013-05-02 18:25:49

标签: java multithreading tcp client

我一般都是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,代码似乎能够读取每个发送请求的响应,但当然无法读取事件消息。

我感谢任何帮助。

谢谢:)

0 个答案:

没有答案