首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TCP Communication+ Java Socket + ReadTimeoutException

TCP Communication+ Java Socket + ReadTimeoutException
EN

Stack Overflow用户
提问于 2015-03-20 23:22:59
回答 1查看 316关注 0票数 0

我正在Tandem系统(Unix环境)中部署我的应用程序。我正在尝试使用TCP连接到其他应用程序。我有IP地址和端口号。从客户端(我的应用程序),我正在写入数据,看起来它正在工作(没有得到任何异常),但在读取数据时,我得到了ReadTimeOutException。下面是我的程序,我将感谢你的帮助。有相同的应用程序返回为C++,它使用相同的IP地址和端口号工作得很好

代码语言:javascript
复制
                Socket clientSocket = new Socket();
                clientSocket.setKeepAlive(true);
                clientSocket.setReuseAddress(true);
                clientSocket.setTcpNoDelay(true);
                clientSocket.setSoTimeout(120000); 
                clientSocket.setSendBufferSize(65535);
               clientSocket.connect(new InetSocketAddress("Server IP", "Port Number"), 1000);
                OutputStream outstream = clientSocket.getOutputStream(); 
                outstream .writeInt(msgLen);
                dout.write(msg, 0, msgLen);
                dout.flush();

                DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
                 int len = din.readInt();
                 data = new byte[len];
                 dis .readFully(data);

它在读它的时候抛出一个错误。尝试建立套接字连接时超时。java.net.SocketTimeoutException:读取超时

===========================

代码语言:javascript
复制
        Socket clientSocket = new Socket();
        clientSocket.setKeepAlive(true);
        clientSocket.setReuseAddress(true);
        clientSocket.setTcpNoDelay(true);
        clientSocket.setSoTimeout(120000); // Should wait 3 minutes before throwing time out exception - Actually throwing after 2 minutes
        clientSocket.setSendBufferSize(65535);

    InputStream in= new ObjectInputStream(socket.getInputStream());
    OutputStream out = new ObjectOutputStream(socket.getOutputStream());
    out.write(byteArray);
    out.flush();


 // Receive the same string back from the server
    int totalBytesRcvd = 0;  // Total bytes received so far
    int bytesRcvd;           // Bytes received in last read
    while (totalBytesRcvd < byteArray.length) {
      if ((bytesRcvd = in.read(byteArray, totalBytesRcvd,  
                      byteArray.length - totalBytesRcvd)) == -1)
        throw new SocketException("Connection close prematurely");
      totalBytesRcvd += bytesRcvd;
    }


    clientSocket .close();  // Close the socket and its streams

请帮我解决这个问题,我从上周开始就被困在这个问题上了。

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2015-03-21 07:05:50

  • 在尝试建立连接时,它没有抛出异常。它在某个ObjectInputStream.
  • 12000调用中抛出它,几乎可以肯定,在ObjectInputStream.的构造函数中,您应该在问题中包括堆栈跟踪。
  • 您需要在读取毫秒之前创建ObjectOutputStream,而不是三分钟。
  • 您应该在客户端使用readFully(),就像在服务器中所做的那样。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29170064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档