简体   繁体   中英

UDP android application works on HTC but not Nexus S

I have a simple application that allows one android device to connect to another, now using my Google Nexus as the host and connecting a client using a HTC Dessire it works fine, but if I run the host as my Google Nexus and my client as a Google Nexus S, it comes up with an error, here is the code for when they try and connect to the server

public void connectToServer()
{
    //Send a connect message to the server
    try {
        //Create a socket
        socket = new DatagramSocket( port );
        byte[] bufer = new byte[256];
        //Send a message "connect" to the host
        String msg = "connect";
        int msgLength = msg.length();
        bufer = msg.getBytes();
        InetAddress address;
        //Default ip address of the host
        address = InetAddress.getByName("192.168.1.59");
        DatagramPacket p = new DatagramPacket( bufer, bufer.length , address, port );
        //Send packet
        socket.send( p ); // <-- Error is here

    } catch (UnknownHostException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //Receive the message back
    byte[] buf = new byte[256];
    DatagramPacket packet = new DatagramPacket( buf, buf.length );
    //Try to receive a packet from the server
    try 
    {
        socket.receive( packet );
    } 
    //Error
    catch (IOException e) 
    {
        Log.d(TAG, "Error with receiving data");
        e.printStackTrace();
    }

    //Convert the packet to a string
    String data = new String( buf, 0, packet.getLength() );

    //Use the string to find out what ID this client is
    ID = Integer.parseInt( data );
    //Setup the client game
    setUpClient();

    //Debug
    //Log.d(TAG, "Data received was :" + ID);
}

Also here is the log from Eclipse

04-02 15:51:56.875: D/gameState(2719): Start the game loop
04-02 15:51:59.754: D/gameState(2719): Coords: x=216.09375,y=387.8023
04-02 15:51:59.754: D/gameState(2719): Join game
04-02 15:51:59.773: E/InputEventReceiver(2719): Exception dispatching input event.
04-02 15:51:59.777: E/MessageQueue-JNI(2719): Exception in MessageQueue callback: handleReceiveCallback
04-02 15:51:59.793: E/MessageQueue-JNI(2719): android.os.NetworkOnMainThreadException
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at libcore.io.IoBridge.sendto(IoBridge.java:473)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at java.net.DatagramSocket.send(DatagramSocket.java:284)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at     com.example.gelorph_v1.gameClient.connectToServer(gameClient.java:89)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at com.example.gelorph_v1.gameClient.<init>(gameClient.java:67)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at com.example.gelorph_v1.gamePanel.changeState(gamePanel.java:153)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at com.example.gelorph_v1.gamePanel.checkCollisions(gamePanel.java:117)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at com.example.gelorph_v1.gamePanel.onTouchEvent(gamePanel.java:77)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.View.dispatchTouchEvent(View.java:7127)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1877)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1877)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1877)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1925)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1379)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.app.Activity.dispatchTouchEvent(Activity.java:2396)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1873)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.View.dispatchPointerEvent(View.java:7307)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3174)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3119)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4155)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4134)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4226)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:171)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.os.MessageQueue.nativePollOnce(Native Method)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.os.MessageQueue.next(MessageQueue.java:125)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.os.Looper.loop(Looper.java:124)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at android.app.ActivityThread.main(ActivityThread.java:4745)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at java.lang.reflect.Method.invokeNative(Native Method)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at java.lang.reflect.Method.invoke(Method.java:511)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-02 15:51:59.793: E/MessageQueue-JNI(2719):   at dalvik.system.NativeStart.main(Native Method)

Any reason why this doesn't work?

Canvas

Update

I have just changed the server and client to be AsyncTask instead of a thread, here is my client code now

@Override
//Keep the game updated
protected String doInBackground(String... params)
{
    //If the client is host, then start the server thread
    if( host == true ) { setUpClient(); server.execute(); }
    //game us now ready to be played
    rdyForPlay = true;
    boolean run = true;
    boolean setupPlayer = false;

    while( run )
    {
        //Tell the server to give position of players
        //if( setupPlayer == true )
        //{
        //  setUpClient();
        //  setupPlayer = false;
        //}

        //If this is a client then do this
        if( host == false )
        {
            try {
                //If the socket is not yet setup, set it up
                if(socket == null)
                {
                    socket = new DatagramSocket( port );
                }
                byte[] bufer = new byte[256];
                //Using the ID given at the start, send X and Y position to the server
                String msg = ID +":"+ assets[ID].returnPosX() +":"+ assets[ID].returnPosY();
                int msgLength = msg.length();
                bufer = msg.getBytes();
                InetAddress address;
                address = InetAddress.getByName("192.168.1.59");
                DatagramPacket p = new DatagramPacket( bufer, bufer.length , address, port );
                //Send the data
                socket.send( p );

            } catch (UnknownHostException e2) {
                // TODO Auto-generated catch block
                Log.d(TAG, "Error with unknown host");
                e2.printStackTrace();
            } catch (SocketException e) {
                // TODO Auto-generated catch block
                Log.d(TAG, "Error with socket");
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.d(TAG, "Error with sending/receiving data");
                e.printStackTrace();
            }

            //Receive the data from the serever
            byte[] buf = new byte[256];
            DatagramPacket packet = new DatagramPacket( buf, buf.length );
            //Try and receive data from the server
            try 
            {
                socket.receive( packet );
            } 
            //Error
            catch (IOException e) 
            {
                Log.d(TAG, "Error with receiving data");
                e.printStackTrace();
            }

            String data = new String( buf, 0, packet.getLength() );
            //Split the string up
            String[] dataArray = data.split("#");
            int newTotalPlayers = Integer.parseInt( dataArray[0] );
            //Using the string do this
            if( newTotalPlayers != totalPlayers )
            {
                Log.d(TAG," what is total amount of players:" + newTotalPlayers);
                if( newTotalPlayers == 1 )
                {
                    newPlayer( 0 );
                    totalPlayers = newTotalPlayers;
                }
                else
                {
                    newPlayer( newTotalPlayers );
                    totalPlayers = newTotalPlayers;
                }
            }

            //Do a for loop to go through dataArray
            for( int i = 0; i < totalPlayers; i++)
            {
                //Update each user that is connected
                String[] pos = dataArray[(i + 1)].split(":");
                if( Integer.parseInt( pos[(i*3)] ) == ID )
                {
                    Log.d(TAG, "Do nothing please");
                }
                else
                {
                    assets[i].setPosition( Integer.parseInt( pos[(i*3) + 1] ), Integer.parseInt( pos[(i*3) + 2] ) );
                }
            }

        }

        //Host data will ofcourse be differnet

    }
    Log.d(TAG, "Error with run value");
    return "finished";
}

I still get the same error... did I implement AsyncTask wrong?

You are running the network operation in the UI thread (hence the exception android.os.NetworkOnMainThreadException ) this is not allowed in newer versions of Android. Use AsyncTask for this instead.

Make sure you call your method in doBackground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM