Android UDP套接字只发送一次数据?

时间:2012-04-14 13:04:05

标签: android multithreading sockets udp

我很擅长编写Android应用程序,我想写一段代码,定期播放传感器数据,比如1秒。搜索开源代码我设法编写了一个发送者类,如下所示:

public class Sender extends Thread {
    private static final String TAG = "Sending";
    private static final int PORT = 12346;
    private static final int TIMEOUT_MS = 500;
    private static final int BUF_SIZE = 1024;
    private WifiManager mWifi;

    Sender(WifiManager wifi) {
        mWifi = wifi;
    }

    public void run() {
        try {
            DatagramSocket socket = new DatagramSocket(PORT);
            socket.setBroadcast(true);
            socket.setSoTimeout(TIMEOUT_MS);
            sendData(socket);
            socket.close();
            Thread.sleep(1000);
        }
        catch (IOException ioe) {
            Log.e(TAG, "Couldn't send data", ioe);
        } 
        catch (InterruptedException ie) {
            Log.e(TAG,  "Can't sleep", ie);
        }
    }

    private void sendData(DatagramSocket socket) throws IOException {
        byte[] buf = new byte[BUF_SIZE];
        buf = object.toString().getBytes();
        InetAddress addr = InetAddress.getByName("192.168.0.255"); // TO FIX
        DatagramPacket packet = new DatagramPacket(buf, buf.length, addr, PORT);
        socket.send(packet);
    }

    public void main(String[] args) {
        new Sender(null).start();
        while (true) {
        }
    }
}

以下是我在onCreate方法中启动它的方法:

public void onCreate(Bundle savedInstanceState) {
...

    new Sender((WifiManager) getSystemService(Context.WIFI_SERVICE)).start();
...
}

现在,如果我在笔记本电脑上打开Wireshark,我只看到应用程序启动时发送的一个数据包而不是每一秒。

有人可以指出我做错了吗?老实说,我对线程和东西并不熟悉,所以我可能只是遗漏了一些明显的东西......

修改

好的,所以必须循环run方法。请参阅以下答案中的更正代码。

1 个答案:

答案 0 :(得分:2)

这是更正的运行方法代码:

public void run() {
            while (true) {
                try {
                    DatagramSocket socket = new DatagramSocket(PORT);
                    socket.setBroadcast(true);
                    socket.setSoTimeout(TIMEOUT_MS);
                    sendData(socket);
                    socket.close();
                    Thread.sleep(1000);
                }
                catch (IOException ioe) {
                    Log.e(TAG, "Couldn't send data", ioe);
                } 
                catch (InterruptedException ie) {
                    Log.e(TAG,  "Can't sleep", ie);
                }
            }
}