UDP-Connections within the emul

Hello Guys,

TCP seems to be a kind of problem !

For now I succeeded, to send data between two UDP-Connections within the emulator. The Log:

Java:
D/UDP ( 1515 ): S: Connecting...
D/UDP ( 1515 ): S: Receiving...
D/UDP ( 1515 ): C: Connecting...
D/UDP ( 1515 ): C: Sending: 'Hello from Client'
D/UDP ( 1515 ): S: Received: 'Hello from Client'
D/UDP ( 1515 ): S: Done.
D/UDP ( 1515 ): C: Sent.
D/UDP ( 1515 ): C: Done.



I'll have a look for some working TCP-Stuff

The code below will be put into an tutorial right now.

Java:
public class UDPConnection extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate (Bundle icicle ) {
        super. onCreate (icicle );
        setContentView (R. layout. main );
       
        Thread sThread = new Thread ( new Server ( ) );
        Thread cThread = new Thread ( new Client ( ) );
       
        sThread. start ( );
        try {
                Thread. sleep ( 500 );
           } catch ( InterruptedException e ) { }
       
          cThread. start ( );
    }
}



Java:
public class Server implements Runnable {
      public static final String SERVERIP = "127.0.0.1";
      public static final int SERVERPORT = 4444;
          
     @Override
      public void run ( ) {
           try {
               Log. d ( "UDP", "S: Connecting..." );
                InetAddress serverAddr = InetAddress. getByName (SERVERIP );
                DatagramSocket socket = new DatagramSocket (SERVERPORT,serverAddr );
                byte [ ] buf = new byte [ 17 ];
                DatagramPacket packet = new DatagramPacket (buf, buf. length );
               Log. d ( "UDP", "S: Receiving..." );
               socket. receive (packet );
               Log. d ( "UDP", "S: Received: '" + new String (packet. getData ( ) ) + "'" );
               Log. d ( "UDP", "S: Done." );
           } catch ( Exception e ) {
               Log. e ( "UDP", "S: Error", e );
           }
      }
}



Java:
public class Client implements Runnable {
     @Override
      public void run ( ) {
           try {
               Log. d ( "UDP", "C: Connecting..." );
                DatagramSocket socket = new DatagramSocket ( );
                byte [ ] buf = ( "Hello from Client" ). getBytes ( );
                InetAddress serverAddr = InetAddress. getByName (Server. SERVERIP );
                DatagramPacket packet = new DatagramPacket (buf, buf. length, serverAddr, Server. SERVERPORT );
               Log. d ( "UDP", "C: Sending: '" + new String (buf ) + "'" );
               socket. send (packet );
               Log. d ( "UDP", "C: Sent." );
               Log. d ( "UDP", "C: Done." );
           } catch ( Exception e ) {
               Log. e ( "UDP", "C: Error", e );
           }
      }
}



Regards,
plusminus

你可能感兴趣的:(java,thread,exception,socket,String,byte)