Android实现UDP通信

TCP和UDP的不同

上次我们讲的是TCP的socket,他们之间的不同在于,tcp要等待客户端的接入,然后获得 客户端socket然后进行IO操作,udp直接传送数据即可

 

 图片来源:面试官:说说UDP和TCP的区别及应用场景 - 知乎 (zhihu.com)

UDPserver的Main.java

DatagramSocket socket = new DatagramSocket(12345);
                // 2.创建数据报,用于接收客户端发送的数据
                byte[] data = new byte[1024];// 创建字节数组,指定接收的数据包的大小
                DatagramPacket packet = new DatagramPacket(data, data.length);
                System.out.println("****服务器端已经启动,等待客户端发送数据");
                socket.receive(packet);// 此方法在接收到数据报之前会一直阻塞
                // 4.读取数据
                String info = new String(data, 0, packet.getLength());
                System.out.println("我是服务器,客户端说:" + info);

                InetAddress address = packet.getAddress();
                int port = packet.getPort();
                byte[] data2 = "欢迎您!".getBytes();
                // 2.创建数据报,包含响应的数据信息
                DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, port);
                // 3.响应客户端
                socket.send(packet2);
                // 4.关闭资源
                socket.close();

Android的MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread() {
            @Override
            public void run() {
                try {
                    udpClient();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    void udpClient() throws IOException {
        InetAddress address = InetAddress.getByName("10.32.108.182");
        int port = 12345;
        byte[] data = "the message you want to send to server".getBytes();
        // 2.创建数据报,包含发送的数据信息
        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
        // 3.创建DatagramSocket对象
        DatagramSocket socket = new DatagramSocket();
        // 4.向服务器端发送数据报
        socket.send(packet);

        byte[] data2 = new byte[1024];
        DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
        // 2.接收服务器响应的数据
        socket.receive(packet2);
        // 3.读取数据
        String reply = new String(data2, 0, packet2.getLength());
        Log.e("tag","我是客户端,服务器说:" + reply);
        // 4.关闭资源
        socket.close();
    }
}

权限

 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

GitHub地址 下载前给star

posted @ 2022-11-05 09:30  Z_Chan  阅读(2176)  评论(0编辑  收藏  举报