这是我在stackoverflow上的第一篇文章...... 几个星期前我正在处理Android应用程序,所以我的Knoledge是有限的。
我想发送和接收UDP pakets enery 5秒。我找到了示例代码但它使用了一个按钮。
class Client实现Runnable { 公共客户() { }
@Override
public void run() {
try
{
String outMessage = txtOutMessage.getText().toString();
String outIp = txtOutIp.getText().toString();
int outPort = Integer.parseInt(txtOutPort.getText().toString());
InetAddress serverAddr = InetAddress.getByName(outIp);
DatagramSocket socket = new DatagramSocket();
byte[] buf = outMessage.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, outPort);
socket.send(packet);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
final String recvMsg = new String(receivePacket.getData()).trim();
runOnUiThread(new Runnable()
{
@Override
public void run() {
txtInMessage.setText(recvMsg);
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
请指教 提前致谢 尼科斯
答案 0 :(得分:0)
为什么不尝试使用线程?像这样的东西会起作用:
//create a thread
Thread t = new Thread()
{
@Override
public void run()
{
while (true)
{
try
{
//do your stuff
Thread.sleep(5000);
//thread to sleep for 5 seconds (5000 milliseconds)
} catch (InterruptedException ie)
{
ie.printStackTrace(); //catch the exception for thread.sleep
}
}
}
};
t.start(); //start the thread
我有一些非常类似的东西,但是我的检查输入数据是100毫秒,并且每250毫秒检查一次传出数据,我每个都有一个线程,然后我有一个单独的线程,每隔20秒运行一次检查套接字确保它存活并进行一些套接字验证,并在失败时创建一个新套接字。