实现PC端与手机端的UDP通信

网上的资料很多,也很杂.所以自已参考了网上的代码实现了UDP的简单通信.在实现的过程的遇到了很多的坑.在这要强调一个基础点,当你用网络调试助手发送UDP消息到安卓模拟器的时候,端口号并不是你本机的端口号.模拟器会有一个自已的端口号,本人在这就吃过很大的亏.导致数据一直接收不到.接下来贴上简单的实现代码.
MainActivity
public class MainActivity extends Activity {

    private static String LOG_TAG = "WifiBroadcastActivity";
    private boolean start = true;
    private EditText IPAddress;
    private String address;
    public static final int DEFAULT_PORT = 43708;
    private static final int MAX_DATA_PACKET_LENGTH = 40;
    private byte[] buffer = new byte[MAX_DATA_PACKET_LENGTH];
    Button startButton;
    Button stopButton;
    TextView label;

    private DatagramSocket msocketClient;
    private DatagramPacket Packet_Receive;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IPAddress = (EditText) this.findViewById(R.id.address);
        startButton = (Button) this.findViewById(R.id.start);
        stopButton = (Button) this.findViewById(R.id.stop);
        label = (TextView) this.findViewById(R.id.label);
        startButton.setEnabled(true);
        stopButton.setEnabled(false);


        //new Thread(new TcpReceive()).start();
        Open();
        address = getLocalIPAddress();
        if (address != null) {
            IPAddress.setText(address);
        } else {
            IPAddress.setText("Can not get IP address");

            return;
        }
        startButton.setOnClickListener(listener);
        stopButton.setOnClickListener(listener);
    }

    private View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            label.setText("");
            if (v == startButton) {
                start = true;

                new BroadCastUdp(IPAddress.getText().toString()).start();
                startButton.setEnabled(false);
                stopButton.setEnabled(true);
            } else if (v == stopButton) {
                start = false;
                startButton.setEnabled(true);
                stopButton.setEnabled(false);
            }
        }
    };

    private String getLocalIPAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(LOG_TAG, ex.toString());
        }
        return null;
    }

    public class BroadCastUdp extends Thread {
        private String dataString;
       // private DatagramSocket udpSocket;

        public BroadCastUdp(String dataString) {
            this.dataString = dataString;
        }

        public void run() {
            DatagramPacket dataPacket = null;

            try {
               // udpSocket = new DatagramSocket(DEFAULT_PORT);

                dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);
                byte[] data = dataString.getBytes();
                dataPacket.setData(data);
                dataPacket.setLength(data.length);
                dataPacket.setPort(DEFAULT_PORT);

                InetAddress broadcastAddr;

              //  broadcastAddr = InetAddress.getByName("255.255.255.255");
              //这里写目的IP地址
                broadcastAddr = InetAddress.getByName("10.10.0.18");
                dataPacket.setAddress(broadcastAddr);
            } catch (Exception e) {
                Log.e(LOG_TAG, e.toString());
            }
            // while( start ){
            try {
               // udpSocket.send(dataPacket);
                if (msocketClient!=null){
                    msocketClient.send(dataPacket);
                }
                sleep(10);
            } catch (Exception e) {
                Log.e(LOG_TAG, e.toString());
            }
            // }

           // udpSocket.close();

        }
    }

    public void Open() {
        try {
            msocketClient = new DatagramSocket(43708);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (msocketClient != null) {
            new Thread(UdpReceiver).start();
        }
    }

    Runnable UdpReceiver = new Runnable() {
        @Override
        public void run() {
            while (true) {
                byte[] Buffer_Receive = new byte[1024];
                Packet_Receive = new DatagramPacket(Buffer_Receive, 1024);
                if (Packet_Receive != null) {
                    try {
                        msocketClient.receive(Packet_Receive);
                        int length = Packet_Receive.getLength();
                        if (length > 0) {
                            final String data = new String(Packet_Receive.getData());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    label.setText(data);
                                }
                            });
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

activity.xml的代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <EditText
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/start"/>

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/stop"/>

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />
</LinearLayout>

在这次测试里我用网络调试助手当做PC的发送和接收测试工具
这里写图片描述

此时我模拟器端的界面如图下所示
这里写图片描述

上述代码可以直接copy使用, 也可以直接下载压缩包:http://download.csdn.net/detail/aino0613/9867336

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值