Android devices to quickly find a particular LAN IP address (UDP communication)

Requirements: udp transmission by way of a device to quickly find local area network within the same
train of thought: the need for a device to send, cell phone reception. Or cell phone transmission, the receiving device, the two devices should be within the same LAN
1, the establishment of service udpsocket
2, to provide data, encapsulating the data packet to
3, socket services by sending the packets sent.
4. Close the resource.
DatagramSocket: This class represents a socket for sending and receiving datagram packets. Always enable UDP broadcasts on DatagramSocket.
DatagramPacket: This class represents a datagram packet. Datagram packets are used to implement a connectionless packet delivery service. Each packet based only on information contained in the packet routed from one machine to another machine. Sent from one machine to another machine a plurality of packets may be routed differently, or may arrive in a different order. Packet delivery is not guaranteed.

Look at a map:

UDP data transmitting
Here Insert Picture Description
UDP data received
Here Insert Picture Description

Specific code as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ui.activity.TestActivity">

    <Button
        android:id="@+id/btn_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送" />

    <Button
        android:id="@+id/btn_wait"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始等待接收" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <TextView
            android:id="@+id/tv_data"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="-------------" />
    </ScrollView>
</LinearLayout>
package com.fzm.coldwallet.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.fzm.coldwallet.R;
import com.fzm.coldwallet.ui.base.BaseActivity;
import com.fzm.coldwallet.utils.ToastUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TestActivity extends BaseActivity {

    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.btn_wait)
    Button btnWait;
    @BindView(R.id.tv_data)
    TextView tvData;
    private MainHandle mMainHandle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        ButterKnife.bind(this);
        mMainHandle = new MainHandle();

    }

    @OnClick({R.id.btn_send, R.id.btn_wait})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_send:
                sendMsg();
                break;
            case R.id.btn_wait:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        waitMsg();
                    }
                }).start();
                break;
        }
    }

    private String sLog = "";

    private void sendMsg() {
        try {
            final DatagramSocket hostSocket = new DatagramSocket();
            // 设置接收超时时间
            hostSocket.setSoTimeout(1500);
            final String sendData = "my name is zzz";
            InetAddress broadIP = InetAddress.getByName("255.255.255.255");
            final DatagramPacket sendPack = new DatagramPacket(sendData.getBytes(), sendData.length(), broadIP, 9901);

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    String log = sendData + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n";
                    Log.v("tag", Thread.currentThread() + log);
                    if (sLog.split("\n").length > 10) {
                        sLog = "";
                    }
                    try {
                        hostSocket.send(sendPack);
                        sLog += log;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvData.setText(sLog);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }, 0, 1000);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private String rLog = "";

    private void waitMsg() {
        byte[] buffer = new byte[1024];
        /*在这里同样使用约定好的端口*/
        int port = 9901;
        DatagramSocket server = null;
        try {
            server = new DatagramSocket(port);
            final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            while (true) {
                // 等待主机的搜索
                try {
                    server.receive(packet);
                    final String s = new String(packet.getData(), 0, packet.getLength(), "UTF-8");
                    String log = packet.getAddress() + ",port:" + packet.getPort() + "," + s + "\n";
                    Log.v("tag", log);
                    rLog += log;
                    if (rLog.split("\n").length > 10) {
                        rLog = "";
                    }
                    mMainHandle.sendEmptyMessage(1);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } finally {
            if (server != null)
                server.close();
        }
    }

    class MainHandle extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tvData.setText(rLog);
        }
    }
}

Finally, do not forget to network permissions:

    <uses-permission android:name="android.permission.INTERNET" />
Published 55 original articles · won praise 93 · views 330 000 +

Guess you like

Origin blog.csdn.net/zx_android/article/details/101065636