简体   繁体   中英

UDP send data from one device to another

I'm trying to send over a small packet from one device to another, My device ip is 192.168.1.59 which is the host, Here is my server code

public class gameServer extends Thread{

/**
 * Sets up a server for Android applciation
 */
private static final String TAG = "GameServer";
private DatagramSocket socket;
private int port = 50000;
private InetAddress local = null;

public gameServer(  ) throws IOException
{
    socket = new DatagramSocket( port );
    Log.d(TAG, "Server was setup");
}

private String getLocalIPAddress()
{
    try
    {
        for (Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); nis.hasMoreElements();)
        {
            NetworkInterface ni = nis.nextElement();
            Log.v(TAG, "NetworkInterface = " + ni.getDisplayName());
            for (Enumeration<InetAddress> ips = ni.getInetAddresses(); ips.hasMoreElements();)
            {
                InetAddress ip = ips.nextElement();
                String s = ip.getHostAddress();
                Log.v(TAG, "InetAddress = " + s);
                if (!ip.isLoopbackAddress())
                {
                            if(InetAddressUtils.isIPv4Address(s)) return s;
                }
            }
        }
    }
    catch (SocketException e)
    {
            Log.e(TAG,"getLocalIPAddress()", e);
    }
    return null;
}

public void passClient( gameObject clientTemp )
{

}

@Override
public void run()
{
    Log.d(TAG, "Ip address used:" + getLocalIPAddress() );
    while( true )
    {
        //Send some data
        try 
        {
            local = InetAddress.getByName("127.0.0.1");
        } 
        catch (UnknownHostException e2) {
            e2.printStackTrace();
        }
        String msg = "hello there";
        int msgLength = msg.length();
        byte[] message = msg.getBytes();
        DatagramPacket p = new DatagramPacket( message, msgLength, local, port );
        try 
        {
            socket.send( p );
        } 
        catch (IOException e2) 
        {
            Log.d(TAG, "Error with sending");
            e2.printStackTrace();
        }

    }
}
}

Here is my client

public class gameClient extends Thread {

private static final String TAG = "gameClient";
private gameServer server;
private boolean rdyForPlay = false;
private ArrayList<gameObject> assets = new ArrayList();
private int ID = 0;
private maths cal = new maths();

public gameClient( boolean serverTag )
{
    if( serverTag == true)
    {
        try 
        {
            server = new gameServer();
            server.run();
        } 
        catch (IOException e) 
        {
            Log.d(TAG, "Could not start server");
            e.printStackTrace();
        }
    }
    else
    {
        //DELETE!!!
        //ONLY FOR TESTING
        DatagramSocket socket = null;;
        try 
        {
            socket = new DatagramSocket( 50000 );
        } 
        catch (SocketException e1) 
        {
            e1.printStackTrace();
        }

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

        String data = new String( buf, 0, packet.getLength() );

        Log.d(TAG, "Data received was :" + data);


    }
}

public void sendTouchEvent(float xSet, float ySet)
{

}

@Override
public void run()
{

}

private void updateAssets()
{

}
}

When the code tries to receive a packet it just crashs on the socjet.receive( packet ); can anyone see any reason why?

Canvas

Your problem is that you have two try blocks. If the first one catches something socket stays null . So do something like that:

 DatagramSocket socket = null;
    try 
    {
        socket = new DatagramSocket( 50000 );
        byte[] buf = new byte[256];
        DatagramPacket packet = new DatagramPacket( buf, buf.length );
        socket.receive( packet );
    } 
    catch (SocketException e1) 
    {
        e1.printStackTrace();
    }
    catch (IOException e) 
    {
        Log.d(TAG, "Error with receiving data");
        e.printStackTrace();
    }

Make sure to close() the socket onDestroy of your Activity!

Also consider AutoDiscovery instead of static IP's: AutoDiscovery

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