Android 两部手机通过UDP在局域网内通信

时间:2021-12-02 03:21:48

最近学习了一下socket通信相关的知识,决定从UDP进行文字传输开始做起。华为手机效果如图:

Android 两部手机通过UDP在局域网内通信

我的另一部是小米手机:网络IP为192.168.1.118 就不截图了,这部华为手机IP为192.168.1.102,注意上面填写的IP为接收方的IP而不是自己的IP

点击发送按钮,开始发送消息:

private DatagramSocket sendSocket = null;
private int sendPort = 8856;

private void sendMsg() {
    try {
        if (sendSocket == null) {
            sendSocket = new DatagramSocket(sendPort);
        }
        InetAddress inetAddress = InetAddress.getByName(tvReceiveIp.getText().toString());
        byte[] bytes = tvServiceMsg.getText().toString().getBytes();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, inetAddress, receivePort);
        sendSocket.send(datagramPacket);
        mHandler.sendEmptyMessage(0);
        System.out.println("MainActivity = " + "发送成功");
        isRunning = true;
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

另一部手机点击接收,开始接收:

private DatagramSocket receiveSocket = null;
private int receivePort = 8855;
DatagramPacket datagramPacket;
private void receiveMsg() {
    try {
        while (isRunning) {
            if (receiveSocket == null) {
                receiveSocket = new DatagramSocket(receivePort);
            }
            byte[] bytes = new byte[1024];
            datagramPacket= new DatagramPacket(bytes, 0, bytes.length);
            receiveSocket.receive(datagramPacket);
            mHandler.sendEmptyMessage(1);

            System.out.println("Main2Activity接收成功 = " + new String(datagramPacket.getData()));
        }

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

发送和接收到的消息通知主线程刷新:

Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case 0:
                creatMessageBean(tvServiceMsg.getText().toString(), true);
                break;
            case 1:
                creatMessageBean(new String(datagramPacket.getData()), false);
                break;
        }
    }
};
private void creatMessageBean(String msg, boolean isSend) {
    MessageBean messageBean = new MessageBean(msg, isSend);
    mAdapter.setData(messageBean);
}

这样一个简单的通信demo就完成了,当然在demo中我没有做严谨的校验,只是为了实现整个流程

demo下载地址为:点击打开链接