gpt4 book ai didi

java - 在 Android 上运行的 UDP 服务器用于 LAN

转载 作者:行者123 更新时间:2023-12-01 04:25:30 25 4
gpt4 key购买 nike

我有服务器和客户端在 LAN 中运行,但我的服务器不接受来自客户端应用程序的多于一条消息。在 LAN 中,我应该在 while 循环中放入什么代码才能接受从客户端应用程序发送的尽可能多的消息?我的服务器类是:

 public class MainActivity extends Activity {
private Boolean shouldRestartSocketListen=true;
TextView tv1;
//MulticastLock lock;
static String UDP_BROADCAST = "UDPBroadcast";
DatagramSocket socket;
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);



startListenForUDPBroadcast();
// lock.release();
}


private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception {
byte[] recvBuf = new byte[15000];
if (socket == null || socket.isClosed()) {
socket = new DatagramSocket(port, broadcastIP);
//socket.setBroadcast(true);
}
//socket.setSoTimeout(1000);
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
Log.e("UDP", "Waiting for UDP broadcast");
socket.receive(packet);

String senderIP = packet.getAddress().getHostAddress();
String message = new String(packet.getData()).trim();

// Log.e("UDP", "Got UDB broadcast from " + senderIP + ", message: " + message);
tv1.setText(message);

// broadcastIntent(senderIP, message);
socket.close();

}
private void broadcastIntent(String senderIP, String message) {
Intent intent = new Intent(MainActivity.UDP_BROADCAST);
intent.putExtra("sender", senderIP);
intent.putExtra("message", message);
sendBroadcast(intent);
}
Thread UDPBroadcastThread;

void startListenForUDPBroadcast() {
UDPBroadcastThread = new Thread(new Runnable() {
public void run() {
try {
InetAddress broadcastIP = InetAddress.getByName("192.168.1.255"); //172.16.238.42 //192.168.1.255
Integer port = 11111;
while (shouldRestartSocketListen) {
listenAndWaitAndThrowIntent(broadcastIP, port);
}
//if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
} catch (Exception e) {
Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
}
}
});
UDPBroadcastThread.start();
}



void stopListen() {
shouldRestartSocketListen = false;
socket.close();
}

public void onCreate() {

};

@Override
public void onDestroy() {
stopListen();
}
public IBinder onBind(Intent intent) {
return null;
}
}

最佳答案

不要关闭套接字,除非您想停止监听(将其放在 while 循环之外)。

我尝试使用 McAfee 的 UDPFlood v2.0,使用像您一样的 socket.close() ,一旦每秒超过 5 个数据包,您就会错过消息(取决于您其他任务的速度) )。消息在您的套接字(操作系统)中缓冲,但您可以通过关闭它来丢弃它们。

关于java - 在 Android 上运行的 UDP 服务器用于 LAN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18546771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com