消除通过tcp / ip发送字符串的延迟

时间:2011-05-23 11:51:12

标签: java android sockets tcp

我的项目有一个灯开关,它有一个IP地址和端口,并接受要控制的字符串。我正在尝试创建一个应用程序来打开和关闭它。 我的代码工作正常,但是在第一次点击后,下一次点击和交换机实际切换之间存在明显的延迟。

我有一个开关按钮。 main.java:

package com.android.lswitch;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class lightswitch extends Activity {
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Handle swon button
    Button swon = (Button) findViewById(R.id.swon);
    swon.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            sw(true);
        }
    });

    // Handle swoff button
    Button swoff = (Button) findViewById(R.id.swoff);
    swoff.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            sw(false);
        }
    });


}

private void sw(boolean swstate) {
    if (swstate == true) {
        Thread swonThread = new Thread(new swon());
        swonThread.start();    
    }

    if (swstate == false) {
    Thread swoffThread = new Thread(new swoff());
    swoffThread.start();    
    }

}
}

和java上的按钮:     包com.android.lswitch;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class swon implements Runnable {
public static final String SERVERIP = "10.0.0.25";
public static final int SERVERPORT = 4000;


public void run(){
try {
    InetAddress serverAddr = InetAddress.getByName(SERVERIP);

    Socket socket = new Socket(serverAddr, SERVERPORT);

    String swon = "A55A6B0550000000FFFBDE0030C8";
    String but0 = "A55A6B0500000000FFFBDE002066";

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

    out.println(swon);
    out.println(but0);
    socket.close();
} catch(Exception e) {
}
    finally {

    }
}
}

按钮关闭几乎相同但具有不同的字符串。 我是android编码(和java编码)的新手,所以无法看到保持的位置。我需要在某处冲洗琴弦吗?还是有更好的方法来解决这个项目?

干杯

1 个答案:

答案 0 :(得分:1)

PrintWriter可能是缓冲的,所以在对底层套接字发出任何flush()操作之前,你绝对应该close()

最好拨打PrintWriter.close()而不是Socket.close(),例如,在finally块中,例如:

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

try {
  out.println(swon);
  out.println(but0);
  out.flush();
} finally {
  out.close();
}