|
| DatagramSocket (Port port, std::size_t bufferSize=2048) |
| Constructs a UDP socket optionally bound to a local port.
|
| DatagramSocket (std::string_view host, Port port, std::size_t bufferSize=2048) |
| Construct a datagram socket to a remote host and port.
|
| ~DatagramSocket () noexcept |
| Destructor. Closes the socket and frees resources.
|
| DatagramSocket (const DatagramSocket &)=delete |
| Copy constructor (deleted).
|
DatagramSocket & | operator= (const DatagramSocket &)=delete |
| Copy assignment operator (deleted).
|
| DatagramSocket (DatagramSocket &&other) noexcept |
| Move constructor.
|
DatagramSocket & | operator= (DatagramSocket &&other) noexcept |
| Move assignment operator.
|
void | bind () const |
| Bind the datagram socket to the configured port set in the constructor.
|
void | connect (int timeoutMillis=-1) |
| Connects the datagram socket to the remote host and port with optional timeout handling.
|
size_t | write (const DatagramPacket &packet) const |
| Write data to a remote host using a DatagramPacket.
|
size_t | write (std::string_view message) const |
| Write data to the socket (connected UDP) from a string_view.
|
size_t | write (std::string_view message, std::string_view host, Port port) const |
| Send a datagram to a specific host and port (connectionless UDP).
|
size_t | read (DatagramPacket &packet, bool resizeBuffer=true) const |
| Receives a UDP datagram and fills the provided DatagramPacket.
|
template<typename T> |
T | read () |
| Read a trivially copyable type from the socket (connected UDP).
|
template<typename T> |
T | recvFrom (std::string *senderAddr, Port *senderPort) |
| Receive a datagram into a trivially copyable type.
|
void | close () |
| Close the datagram socket.
|
void | setNonBlocking (bool nonBlocking) const |
| Set the socket to non-blocking or blocking mode.
|
void | setTimeout (int millis) const |
| Sets the socket's receive timeout.
|
void | setOption (int level, int optName, int value) const |
| Set a socket option (integer value).
|
int | getOption (int level, int optName) const |
| Get a socket option (integer value).
|
std::string | getLocalSocketAddress () const |
| Get the local socket's address as a string (ip:port).
|
bool | isValid () const |
| Check if the datagram socket is valid (open).
|
bool | isConnected () const |
| Check if the datagram socket is connected to a remote host.
|
void | enableBroadcast (bool enable) const |
| Enable or disable the ability to send broadcast packets.
|
Cross-platform UDP socket class with Java-style interface.
The DatagramSocket class provides a convenient, cross-platform abstraction for sending and receiving UDP datagrams, inspired by the Java API. It supports both IPv4 and IPv6, and works on Windows and Linux.
What is UDP?
UDP (User Datagram Protocol) is a lightweight, connectionless protocol for sending packets over the network. Unlike TCP, UDP does not guarantee delivery, ordering, or duplicate protection—packets may be lost, arrive out of order, or duplicated. However, UDP is fast and simple, and widely used for real-time applications (such as online games, video streaming, and VoIP).
Key Features
- Connectionless and connected modes: You can send datagrams to any address/port, or "connect" the socket to a default destination for simpler sending/receiving.
- Custom buffer size: Easily set the size of the internal buffer for large or small datagrams.
- Broadcast support: Easily enable broadcast packets.
- Timeouts and non-blocking mode: Set timeouts and switch between blocking/non-blocking operations.
- Java-style interface: Familiar to those who have used Java networking.
Example: Simple UDP Echo Server and Client
#include <iostream>
while (true) {
size_t received = server.read(packet);
std::cout << "Received: " << std::string(packet.buffer.begin(), packet.buffer.end())
<< " from " << packet.address << ":" << packet.port << std::endl;
server.write(packet);
}
}
UDP datagram socket abstraction for jsocketpp.
Represents a UDP datagram packet, encapsulating both payload and addressing information.
Definition DatagramPacket.hpp:48
Cross-platform UDP socket class with Java-style interface.
Definition DatagramSocket.hpp:81
int main()
Definition client.cpp:89
#include <iostream>
std::string message = "Hello UDP!";
client.
write(message,
"127.0.0.1", 12345);
std::cout << "Server replied: " << std::string(response.buffer.begin(), response.buffer.end()) << std::endl;
}
size_t read(DatagramPacket &packet, bool resizeBuffer=true) const
Receives a UDP datagram and fills the provided DatagramPacket.
Definition DatagramSocket.cpp:343
size_t write(const DatagramPacket &packet) const
Write data to a remote host using a DatagramPacket.
Definition DatagramSocket.cpp:232
Notes
- Not thread-safe. Use each DatagramSocket instance from only one thread at a time.
- Use the DatagramPacket class to store both the data and the address/port of the sender/receiver.
- To receive the sender’s address and port, use the read(DatagramPacket&) method.
- See also
- jsocketpp::DatagramPacket
-
jsocketpp::SocketException
void DatagramSocket::connect |
( |
int | timeoutMillis = -1 | ) |
|
Connects the datagram socket to the remote host and port with optional timeout handling.
This function binds the datagram socket to a specific remote destination (host and port) for sending subsequent datagrams. Although UDP is connectionless, calling connect() on a datagram socket allows the socket to send datagrams to a specific destination without needing to specify the address each time.
The connection process works as follows:
- In non-blocking mode, the connection attempt proceeds immediately. If the connection cannot be completed right away, it will return EINPROGRESS (or WSAEINPROGRESS on Windows), indicating that the connection is still in progress.
- select() is used to wait for the socket to be ready for communication within the specified timeout.
- If no timeout is specified (i.e., timeoutMillis < 0), the socket connects in blocking mode, which will block until either the connection completes or an error occurs.
- If the connection fails or times out, an exception is thrown with the relevant error code and message.
This function is cross-platform and works on both Windows and Linux systems.
- Parameters
-
timeoutMillis | The maximum time to wait for the connection to be established, in milliseconds. If set to a negative value, the connection will be attempted in blocking mode (no timeout). If set to a non-negative value, the connection will be attempted in non-blocking mode, and select() will be used to wait for the connection to complete within the specified timeout. |
- Exceptions
-
SocketException | If the connection fails, times out, or if there is an error during the connection attempt. The exception will contain the error code and message describing the failure. |