2

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

1 回答 1

0

不要关闭套接字,除非你想停止监听(把它放在你的 while 循环之外)。

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

于 2013-09-05T16:09:50.617 回答