我有服务器和客户端在 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;
}
}