简体   繁体   English

Android套接字等待问题

[英]Android socket wait issue

Hello I have an app that connect to a remote server using sockets 您好,我有一个使用套接字连接到远程服务器的应用程序

socket = new Socket();
socket.connect(new InetSocketAddress(Ip, portNum), 7000);

I have 2 methods send & receive 我有两种发送和接收方法

the scenario in send is 发送中的场景是

 PrintWriter out = new PrintWriter(socket.getOutputStream(),true);

in method receive 在方法中接收

  String msg = "";
    BufferedReader in = null;

    try {
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));


        while (in.ready()) {

            msg = msg + (char) in.read();

        }
        socket.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

in AsyncTask of a different class I call 在我调用的另一个类的AsyncTask中

 send();
 String response=receive();

The above code is not sending or receiving without a wait period 上面的代码没有等待时间就不会发送或接收

ie

    Thread.sleep(2000);

I know sleep is a bad approach what is the best scenario should I use? 我知道睡眠是一种不好的方法,应该使用哪种最佳方案?

Is it better to make an AsyncTask within send method and another one for receive method. 最好在send方法中创建一个AsyncTask,再在Receive方法中创建一个AsyncTask。

Here is where I use sleep and what data send & receive 这是我使用睡眠的地方以及发送和接收哪些数据

 client.send(some sql statement representED as json format);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
// sql select result represented as json
        String RESULT = client.recive();

Likely your server is not listening before you try to connect. 尝试连接之前,您的服务器可能没有监听。 Though this is unclear from the code you have posted. 尽管您发布的代码尚不清楚。 You'll need to show both server and client code there. 您需要在此同时显示服务器和客户端代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM