3

我正在做一个需要与 TCP 套接字通信的应用程序。我设置了一个作为我的 TCP 服务器的服务和一个作为我的 TCP 客户端的活动。

我在发送消息和从服务器接收答案方面有很大的延迟,比如 10 秒或更长时间。经过几天的研究,我发现了如何在客户端请求上设置超时并且一切都开始正常工作。

所以我的问题是,是否必须为 TCP 连接设置超时,否则它不起作用或我的实现有其他问题?

这是我的客户代码:

public static void sendTCP(final InetAddress senderAddr, final String Msg, final int serverPort) {
        Thread tclient = new Thread(){
            public void run() {
                boolean connected;
                Socket socket = new Socket();
                try {
                    Log.d("TCP", "Client: Connecting...");
                    socket.bind(null);
                    socket.connect((new InetSocketAddress(senderAddr, serverPort)), 1000);
                    connected = true;
                try {
                    Log.d("TCP", "Client: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                    out.println(Msg);
                    out.close();
                } 
                catch (Exception e) {
                    Log.e("TCP", "Client: Error sending.", e);
                }
                } catch (Exception e) {
                    Log.e("TCP", "Client: Error connecting.", e);
                    connected = false;
                }
                finally {
                    if (socket != null) {
                        if (socket.isConnected()) {
                            try {
                                socket.close();
                                Log.d("TCP", "Client: Connection Closed.");
                            } catch (IOException e) {
                                Log.e("TCP", "Client: Error closing connection.", e);
                            }
                        }
                    }
                }
            }
        };
        tclient.start();
    }

和服务器的:

public void onStart(Intent intent, int startid) {

    t = new Thread(){
         public void run() {
             try {
                Boolean end = false;
                Log.d("TCP", "Server: Creating server.");
                ServerSocket ss = new ServerSocket(TCPPORT);
                while(!end) {
                    //Server is waiting for client here, if needed
                    Log.d("TCP", "Server: Waiting on packet!");
                    Socket s = ss.accept();
                    BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    String st = input.readLine();
                    Log.d("TCP", "Server: Message received from client: "+st);

                    InetAddress senderAddr = s.getInetAddress();
                    senderAddrString= senderAddr.getHostAddress();

                    myAddrString = GetLocalIpAddress();
                    myAddr = InetAddress.getByName(myAddrString);

                    if (senderAddr.equals(myAddr)) {
                    }
                    else {
                        //Estraggo dal pacchetto ricevuto
                        try {
                            StringTokenizer tokens = new StringTokenizer(st, "|");
                            flag = tokens.nextToken();
                            userid = tokens.nextToken();
                            payload = tokens.nextToken();
                        }
                        catch (Exception e) {
                            Log.e("TCP", "Server: Errore estrazione dati.");
                        }

                        if (flag.equals(Constants.flag_scan_answer)) {
                            Log.d("TCP", "Server: Flag answer");
                            //devo passare i dati ad un database ScanActivity

                            //database(senderAddrString,userid);

                            System.out.println("RISPOSTA RICEVUTA DAL SERVICE TCP");
                            System.out.println("FLAG " + flag);
                            System.out.println("USERID " + userid);
                            System.out.println("PAYLOAD " + payload);

                            announceReceivingPacket();
                        }

                        else {
                            Log.d("TCP", "Server: CASO NON PREVISTO");
                        }
                    }
                    s.close();
                }
            }
            catch (UnknownHostException e) {
                    e.printStackTrace();
            } 
            catch (IOException e) {
                    e.printStackTrace();
            }
         }
    };
    t.start();
 }
4

2 回答 2

3

必须为 TCP 连接设置超时

这不是强制性的,但这是一个非常好的主意。首先将其设置为预期服务时间的两倍或三倍,然后进行调整,以免误报。默认的读取超时是无限的,我已经看到整个平台以一种读取器无法检测到的方式失败,而不是读取超时。

相关报价请参见此处

于 2012-12-07T09:09:36.443 回答
-1

连接调用

socket.connect((new InetSocketAddress(senderAddr, serverPort)), 1000);

可以是带有自动报告失败和超时以及成功连接的回调的 BeginConnect。此时您可以在套接字上使用 BeginSend 和 BeginReceive。

于 2020-09-05T00:14:13.970 回答