我有一个 AsyncTask
在后台创建udp套接字的扩展程序类,当客户端为ip广播时,它返回ip。但有时有用,有时不行。我试着提高优先级 Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
但是有点进步。
这是我的类背景方法:
protected Void doInBackground(String ... strings) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
byte[] messageBytes = new byte[1024];
DatagramPacket received = new DatagramPacket(messageBytes, messageBytes.length);
try {
Log.d(TAG, "udp port: "+port);
DatagramSocket datagramSocket = new DatagramSocket(port);
this.ready=true;
while (running){
try {
datagramSocket.receive(received);
} catch (IOException e) {
}
String message = new String(messageBytes, 0, received.getLength());
if (message.equals(question)){
try {
InetAddress clientIP=received.getAddress();
byte[] msg=answer.getBytes();
DatagramPacket toSend=new DatagramPacket(msg,msg.length,clientIP, port);
datagramSocket.send(toSend);
} catch (IOException e) {
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
datagramSocket.close();
} catch (SocketException e) {
this.ready=false;
}
return null;
}
我就是这么说的 mainActivity
:
TCPServer connectionManager=new TCPServer(); //My main TCP Server Object
connectionManager.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
UDPBroadcastResponder udpBroadcastResponder;//to find server ip
int udpPort=1793; //Find a port not in use
do {
udpBroadcastResponder = new UDPBroadcastResponder(udpPort,
"Who is Stone-Hole Server?", "TCP-IP");
udpBroadcastResponder.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
if (!udpBroadcastResponder.isReady()) {
udpBroadcastResponder.close();
udpBroadcastResponder.cancel(true);
}
udpPort++;
}while ((!udpBroadcastResponder.isReady())&(udpBroadcastResponder.getPort()<1800));//check 7 ports
这是我的网络流量。400毫秒响应后发送的每条消息应为tcp ip:
谁是石洞服务器?
谁是石洞服务器?tcp ip
谁是石洞服务器?tcp ip
谁是石洞服务器?tcp ip
谁是石洞服务器?tcp ip
谁是石洞服务器?
谁是石洞服务器?
谁是石洞服务器?
谁是石洞服务器?
谁是石洞服务器?
谁是石洞服务器?
... 有时需要5分钟以上才能再次响应
暂无答案!
目前还没有任何答案,快来回答吧!