通过TCP Socket然后Telnet连接速度要慢得多

时间:2017-12-17 15:08:45

标签: java android multithreading sockets outputstream

我正在尝试通过本地网络向ESP8266发送命令。 ESP处理命令以打开例如灯。 ESP的代码在这里无关紧要。我的问题是我的Android应用程序的响应时间远高于在同一部手机上使用telnet(app = 2秒,telnet =几乎立即)。我不确定问题是选择的方法来编写数据还是我的方法来实现线程(参见代码)。我尝试了不同的StreamWriters(BufferedOutputstream等),也尝试了线程的优先级,但它仍然没有用。有任何想法吗?

public class NetworkController extends Thread {

private static final String HOST = "192.168.178.69";
private static final int PORT = 50344;
public  boolean isAlive;
public  boolean connected = true;
public MainActivity main;
public Socket client;
private DataInputStream input;
private BufferedOutputStream output;
private BufferedWriter outputWriter;

@Override
public void run() {
    try {
        client = new Socket(HOST, PORT);
        input = new DataInputStream(client.getInputStream());
        output = new BufferedOutputStream(client.getOutputStream());

        outputWriter = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

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

    if(client != null) {
        isAlive = true;
        System.out.println("Is Connected");
        while (connected) {
            if (!MainActivity.commandQueue.isEmpty()) {
                String command = MainActivity.commandQueue.poll();
                command += "\n";
                try {
                    output.write(command.getBytes());

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

        }
    }

    isAlive = false;
    System.out.println("Thread is not reachable for some Reason");

}

}

尽管我的代码现在不能安全使用,但有一个简短的解释:如果有人点击某个按钮,它会将命令添加到commandQueue中,该命令会在此Thread中不断检查。

编辑:我做了一些测试并监控了ESP。问题绝对是outputWriter。线程立即响应,ESP也立即获得第一个数据字节,但整个包(只是短字符串)需要更长的时间才能通过telnet连接进行传输。有没有想过使用快速方法在输出流上写入数据?

0 个答案:

没有答案
相关问题