在android中传输udp包

时间:2015-06-30 12:44:05

标签: android udp

这些代码用于在android中发送和接收udp数据包。当我在模拟器中运行它时,它可以接收数据。但它并不适用于真实设备。什么是问题?

在Eclipse中:

getAnimationConfig: function() {
  var x = 1;
  var y = 2;
  var z = 3;
  return [{
    name: 'transform-animation',
    node: this,
    transformFrom: 'translate3d('+x+'px,'+y+'px,'+z+'px)',
    transformTo: 'translate3d(0,0,0)'
  }]
}

UdpClient.java:

public class UdpServer extends Activity {
/** Called when the activity is first created. */
private TextView textView; 
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView = (TextView) findViewById(R.id.text1);
    runUdpServer();
}
private static final int UDP_SERVER_PORT = 11111;
private static final int MAX_UDP_DATAGRAM_LEN = 1500;
private void runUdpServer() {
    String lText;
    byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
    DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
    DatagramSocket ds = null;
    try {
        ds = new DatagramSocket(UDP_SERVER_PORT);
        //disable timeout for testing
        //ds.setSoTimeout(100000);
        ds.receive(dp);
        lText = new String(lMsg, 0, dp.getLength());
        Log.i("UDP packet received", lText);
        textView.setText(lText);
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ds != null) {
            ds.close();
        }
    }

}
}

清单:

public class UdpClient extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    runUdpClient();
    finish();
}
private static final int UDP_SERVER_PORT = 11111;
private void runUdpClient()  {
    String udpMsg = "hello world from UDP client " + UDP_SERVER_PORT;
    DatagramSocket ds = null;
    try {
        ds = new DatagramSocket();
        InetAddress serverAddr = InetAddress.getByName("127.0.0.1");
        DatagramPacket dp;
        dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);
        ds.send(dp);
    } catch (SocketException e) {
        e.printStackTrace();
    }catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (ds != null) {
            ds.close();
        }
    }
}
}

这是代码链接。 Link 它需要调制解调器吗?它需要连接到互联网吗?是否需要Wi-Fi?

0 个答案:

没有答案