套接字读取需要很多时间

时间:2013-12-27 10:07:18

标签: java sockets

下面是我的客户端代码,我在做Socket写&读操作。在这里,我正在与已定义协议的服务器进行交互。因此,我们向其发送代码消息并阅读响应。但是在下面的代码中:

message_id = din.readInt();

该行长时间运行并在15分钟后返回数据。我不知道为什么需要花费那么多时间,如果有人在此之前遇到过这个问题,请告诉我。

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConnectSaS {

    public static final int REQ_SESOPEN = 128;

    /**
    * @param args
    */
    public static void main(String[] args) {
        Socket socket;

        DataOutputStream out;
        int message_id;
        int persist_session_id;
        int session_id;
        int data_length;
        String connectionString;

        try {
            socket = new Socket("infasas", 11080);
            socket.setSoTimeout(0);
            socket.setTcpNoDelay(true);
            socket.isOutputShutdown();          

            System.out.println("Connection accepted " + socket.getInetAddress()
                    + ":" + socket.getPort() + ":" + socket.getLocalPort());

            out = new DataOutputStream(socket.getOutputStream());
            out.writeInt(REQ_SESOPEN);
            out.writeInt(6);
            out.writeInt(40);
            connectionString = "sasuser sasuser SAS_Connection IS_ps7153";          
            out.write(connectionString.getBytes());

            DataInputStream din = new DataInputStream(socket.getInputStream());

            message_id = din.readInt();
            persist_session_id = din.readInt();
            data_length = din.readInt();
            din.readByte();
            System.out.println("message_id:----" + message_id);
            System.out.println("session_id:----" + persist_session_id);
            System.out.println("data_length:----" + data_length);   
        } catch (Exception e) {
            System.out.println("Problem reading back from server: " + e);
        }   
    }

}

1 个答案:

答案 0 :(得分:1)

需要花费很长时间,因为发送者需要花费很多时间才能发送整数。

调用isOutputShutdown()并丢弃结果是完全没有意义的。