实现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);
   
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值