第 13.4 節

UDP communication

0瀏覽次數0訪問次數--跳出率--平均停留

Linux UDP Communication

UDP communication is a very common method of communication in Linux network programming.

Compared to TCP, UDP doesn't require a connection to be established beforehand—the sender can directly transmit data to a specific IP and port. It features simplicity, low latency, and low overhead, but it doesn't guarantee delivery or order.

In robot projects, UDP is often used for high-frequency, real-time data transmission scenarios that allow a small amount of packet loss.

In practical projects, UDP communication is commonly used for:

  • Lidar data transmission
  • network camera or sensor data stream
  • Robot Status Broadcast
  • LAN device discovery
  • Remote controller or gamepad data transmission
  • Simple communication between multiple robots
  • High-frequency status reporting
  • Scenarios with high real-time requirements but tolerating some packet loss

The core characteristic of UDP is speed, but it is unreliable. Therefore, it is more suitable for "continuous data streams" rather than scenarios where "every message must be guaranteed to be delivered."

What is UDP communication?

UDP, which stands for User Datagram Protocol, is a connectionless transport protocol.

Unlike TCP, UDP communication does not require establishing a connection. As long as you know the destination IP and port, you can send data directly.

A typical structure is as follows:

UDP Sender
    ↓
UDP Receiver

It can also be bidirectional communication:

程序 A  ←UDP→  程序 B

Common concepts include:

conceptExplanation
IP addressused to locate devices in the network
port numberUsed to differentiate between different programs.
DatagramUDP datagram: each send corresponds to one datagram.
broadcastsend data to multiple devices on the local area network
multicastSend data to devices in the same multicast group
packet lossUDP does not guarantee data delivery
Out of OrderUDP does not guarantee that data arrives in order.

The biggest difference between UDP and TCP is: TCP is a reliable byte stream, while UDP is an unreliable datagram.

Common UDP Libraries on Linux

There are multiple approaches for UDP communication under Linux, common ones include:

solutiontypeFeaturesSuitable scenarios
Linux socket APILinux native interfaceLowest level, few dependencies, high versatility.Want to deeply understand network communication mechanisms.
boost::asioGeneral-purpose C++ networking librarySupports synchronous and asynchronous UDP, suitable for engineering encapsulation.Recommended for C++ projects
Qt NetworkQt Network ModuleEasy to integrate with Qt interface programs.Qt host computer
Python socketPython standard librarySimple and convenient, suitable for testing.Python debugging script
ROS 2 topicROS 2 communication mechanismROS 2 internal communication is convenient.ROS 2 Internal Data Transfer

These solutions are essentially all for completing the sending and receiving of UDP datagrams, just with different encapsulation methods.

Comparison of Solutions

solutionAdvantagesDisadvantages
Linux socket APInative, stable, few dependencies, strong versatilityThe code is relatively cumbersome, and asynchronous handling is troublesome.
boost::asioC++ project-friendly, convenient asynchronous UDP, suitable for encapsulating a driver.Need to understand concepts such as io_context, endpoint, socket.
Qt NetworkNaturally integrates with Qt programs, suitable for the host computer.Not suitable to be detached from Qt's underlying driver.
Python socketQuick to get started, suitable for testing UDP packets.Not suitable as the main thread for C++ low-level
ROS 2 topicROS 2 internal communication is convenient.Not suitable as a substitute for general UDP learning.

This tutorial recommends selecting

This tutorial recommends prioritizing:

boost::asio

The reason is:

  • Suitable for C++ engineering development
  • and TCP, serial port, and timers can use the same Boost.Asio programming model
  • Supports synchronous and asynchronous UDP sending and receiving.
  • Does not depend on ROS 2, making it easy to reuse in ordinary C++, OpenCV, Qt, and embedded Linux projects.
  • Suitable for encapsulating functions such as network sensors, remote control, status broadcast, etc.

The recommended project structure is:

上层项目:ROS 2 / OpenCV / Qt / 普通 C++ 程序
        ↓
自己封装的 UdpSender / UdpReceiver 类
        ↓
boost::asio
        ↓
UDP socket
        ↓
雷达 / 网络设备 / 远程控制端

How to choose between TCP and UDP

TCP and UDP are both commonly used, but they are suitable for different scenarios.

Comparison itemTCPUDP
Connect?Need to establish a connection.No need to establish a connection
reliabilityreliable transmissionDelivery is not guaranteed.
order您提到的“保证顺序”指的是在翻译过程中保持原文的段落、列表、代码块等结构顺序不变。请提供需要翻译的简化中文 Markdown 片段,我会严格按照此要求翻译为自然的美式英语,同时保留所有占位符(如 __I18N_PROTECTED_0__)和术语。Order not guaranteed.
delayrelatively higherrelatively lower
Suitable DataCommands, Configuration, Files, LogsHigh-frequency data, broadcast, real-time status
Typical scenariosRemote control, server communication, parameter configurationradar data, remote control data, status broadcast

In simple terms:

TCP:我要确保这条消息送到
UDP:我要快速持续发送,偶尔丢一包也能接受

Relationship with ROS 2

Learning UDP does not mean you should replace ROS 2 topics with UDP.

Inside the ROS 2 system, communication between nodes typically prioritizes using ROS 2’s own communication mechanisms. UDP, on the other hand, is better suited for connecting to network devices outside the ROS 2 system or for implementing lightweight remote communication.

For example:

激光雷达
        ↓
UDP 数据包
        ↓
自己封装的 UdpReceiver
        ↓
ROS 2 节点发布点云 / LaserScan

Can also be used for:

远程遥控端
        ↓
UDP
        ↓
机器人主控程序

Chapter learning objectives

After completing this chapter, you should be able to:

  • Basic Concepts of UDP Communication
  • Main differences between UDP and TCP
  • The meaning of IP address, port number, and endpoint.
  • Send and receive UDP data using C++
  • Understanding UDP packet loss, out-of-order delivery, broadcasting, and other characteristics
  • Wrapping a UDP Communication Class Using Boost.Asio
  • lay the foundation for subsequent radar data reception, remote control, and status broadcast
音乐页