2

我有两个类,一个是发送者类,另一个是接收者类。发送和接收应用程序都在几秒钟后停止并关闭。我的发件人类别是:

    public class MainActivity extends Activity {
InetAddress receiverAddress;
DatagramSocket datagramSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    try {
        datagramSocket = new DatagramSocket(4444);
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    byte[] buffer = "0123456789".getBytes();
    byte[] address="192.168.1.101".getBytes();

    try {
        receiverAddress = InetAddress.getByAddress(address);
    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    DatagramPacket packet = new DatagramPacket(
            buffer, buffer.length, receiverAddress, 4444);

    try {
        datagramSocket.send(packet);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}

我的接收或听力课程是:

public class MainActivity extends Activity {
DatagramSocket datagramSocket;
DatagramPacket packet;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv1=(TextView)findViewById(R.id.textView1);
     try {
        datagramSocket = new DatagramSocket(80);
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    byte[] buffer = new byte[10];
     packet = new DatagramPacket(buffer, buffer.length);

    try {
        datagramSocket.receive(packet);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    byte[] buff = packet.getData();

tv1.setText(buff.toString());

}

在此先感谢您的帮助。

4

3 回答 3

4

在 Android 中,您不允许在 UIThread(主线程)上执行网络操作

要解决这个问题:将您的网络代码复制到一个新线程并让它运行。

于 2014-08-04T12:31:08.597 回答
1

The port numbers in the "new DatagramSocket(...)" calls look weird. The client should create an "unbound" socket - simply use "new DatagramSocket();". The sender should bind to the port that the client sends to, i.e. "new DatagramSocket(4444);".

于 2013-08-25T17:48:39.123 回答
0

Source and destination port number should be same. Give same numbers in "DatagramSocket(xxx)". xxx must be same in both programs.

于 2014-04-19T14:48:01.887 回答