在android上为LAN运行的UDP服务器

时间:2013-08-31 09:48:26

标签: java android sockets network-programming udp

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

 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;
 }
     }

1 个答案:

答案 0 :(得分:0)

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

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