套接字仅在重新连接网络时接收数据

时间:2015-06-17 06:42:41

标签: java android sockets socket.io serversocket

我面临一个奇怪的问题,我已经按照Google Blog为Android编写了一个应用程序。

以下是代码段:

服务器:

 protected DatagramSocket createSocket() throws UnknownHostException, IOException {
     if (mSocket == null) {
                DatagramChannel mChannel = DatagramChannel.open();
                mSocket = mChannel.socket();
                mSocket.setReuseAddress(true);
                mSocket.setBroadcast(true);
                mSocket.bind(new InetSocketAddress(PORT));
            }
     return mSocket; 
}

[在循环内部广播线程]

private void startBroadcast(String message) throws IOException {
    byte[] data = message.getBytes();

    DatagramPacket packet = new DatagramPacket(
            data,
            data.length,
            mBroadcastAddress,
            mBroadcastPort
            );

    mSocket.send(packet);
}

客户:

protected DatagramSocket createSocket() throws IOException {
        if (mSocket == null) {
             DatagramChannel mChannel = DatagramChannel.open();
             mSocket = mChannel.socket();
             mSocket.setReuseAddress(true);
             mSocket.setSoTimeout(10000);
             mSocket.bind(new InetSocketAddress(PORT));
        }
        return mSocket;
    }

protected void receiveIntents() throws IOException {
        while (running) {
            DatagramPacket packet = new DatagramPacket(
                    new byte[MAXIMUM_PACKET_BYTES], MAXIMUM_PACKET_BYTES
            );

            mSocket.receive(packet);

            byte[] data = packet.getData();
            int length = packet.getLength();

            String msg = new String(data, 0, length);

            listener.onBroadCastResponseReceived(packet.getAddress(), msg);
        }
    }

我调试了代码,发现服务器工作正常并按时广播消息。但客户端阻止“mSocket.receive(packet);”。如果我打开/关闭WiFi连接,它会立即开始在同一个插槽上接收消息。

0 个答案:

没有答案