Loading...
Searching...
No Matches

Specialized socket using the UDP protocol. More...

#include <SFML/Network/UdpSocket.hpp>

Inheritance diagram for sf::UdpSocket:
sf::Socket

Public Types

enum class  Status {
  Done , NotReady , Partial , Disconnected ,
  Error
}
 Status codes that may be returned by socket functions. More...
 

Public Member Functions

 UdpSocket ()
 Default constructor.
 
unsigned short getLocalPort () const
 Get the port to which the socket is bound locally.
 
Status bind (unsigned short port, IpAddress address=IpAddress::Any)
 Bind the socket to a specific port.
 
void unbind ()
 Unbind the socket from the local port to which it is bound.
 
Status send (const void *data, std::size_t size, IpAddress remoteAddress, unsigned short remotePort)
 Send raw data to a remote peer.
 
Status receive (void *data, std::size_t size, std::size_t &received, std::optional< IpAddress > &remoteAddress, unsigned short &remotePort)
 Receive raw data from a remote peer.
 
Status send (Packet &packet, IpAddress remoteAddress, unsigned short remotePort)
 Send a formatted packet of data to a remote peer.
 
Status receive (Packet &packet, std::optional< IpAddress > &remoteAddress, unsigned short &remotePort)
 Receive a formatted packet of data from a remote peer.
 
void setBlocking (bool blocking)
 Set the blocking state of the socket.
 
bool isBlocking () const
 Tell whether the socket is in blocking or non-blocking mode.
 

Static Public Attributes

static constexpr std::size_t MaxDatagramSize {65507}
 The maximum number of bytes that can be sent in a single UDP datagram.
 
static constexpr unsigned short AnyPort {0}
 Some special values used by sockets.
 

Protected Types

enum class  Type { Tcp , Udp }
 Types of protocols that the socket can use. More...
 

Protected Member Functions

SocketHandle getNativeHandle () const
 Return the internal handle of the socket.
 
void create ()
 Create the internal representation of the socket.
 
void create (SocketHandle handle)
 Create the internal representation of the socket from a socket handle.
 
void close ()
 Close the socket gracefully.
 

Detailed Description

Specialized socket using the UDP protocol.

A UDP socket is a connectionless socket.

Instead of connecting once to a remote host, like TCP sockets, it can send to and receive from any host at any time.

It is a datagram protocol: bounded blocks of data (datagrams) are transferred over the network rather than a continuous stream of data (TCP). Therefore, one call to send will always match one call to receive (if the datagram is not lost), with the same data that was sent.

The UDP protocol is lightweight but unreliable. Unreliable means that datagrams may be duplicated, be lost or arrive reordered. However, if a datagram arrives, its data is guaranteed to be valid.

UDP is generally used for real-time communication (audio or video streaming, real-time games, etc.) where speed is crucial and lost data doesn't matter much.

Sending and receiving data can use either the low-level or the high-level functions. The low-level functions process a raw sequence of bytes, whereas the high-level interface uses packets (see sf::Packet), which are easier to use and provide more safety regarding the data that is exchanged. You can look at the sf::Packet class to get more details about how they work.

It is important to note that UdpSocket is unable to send datagrams bigger than MaxDatagramSize. In this case, it returns an error and doesn't send anything. This applies to both raw data and packets. Indeed, even packets are unable to split and recompose data, due to the unreliability of the protocol (dropped, mixed or duplicated datagrams may lead to a big mess when trying to recompose a packet).

If the socket is bound to a port, it is automatically unbound from it when the socket is destroyed. However, you can unbind the socket explicitly with the Unbind function if necessary, to stop receiving messages or make the port available for other sockets.

Usage example:

// ----- The client -----
// Create a socket and bind it to the port 55001
socket.bind(55001);
// Send a message to 192.168.1.50 on port 55002
std::string message = "Hi, I am " + sf::IpAddress::getLocalAddress().toString();
socket.send(message.c_str(), message.size() + 1, "192.168.1.50", 55002);
// Receive an answer (most likely from 192.168.1.50, but could be anyone else)
std::array<char, 1024> buffer;
std::size_t received = 0;
std::optional<sf::IpAddress> sender;
unsigned short port;
if (socket.receive(buffer.data(), buffer.size(), received, sender, port) == sf::Socket::Status::Done)
std::cout << sender->toString() << " said: " << buffer.data() << std::endl;
// ----- The server -----
// Create a socket and bind it to the port 55002
socket.bind(55002);
// Receive a message from anyone
std::array<char, 1024> buffer;
std::size_t received = 0;
std::optional<sf::IpAddress> sender;
unsigned short port;
if (socket.receive(buffer.data(), buffer.size(), received, sender, port) == sf::Socket::Status::Done)
std::cout << sender->toString() << " said: " << buffer.data() << std::endl;
// Send an answer
std::string message = "Welcome " + sender.toString();
socket.send(message.c_str(), message.size() + 1, sender, port);
static std::optional< IpAddress > getLocalAddress()
Get the computer's local address.
@ Done
The socket has sent / received the data.
Specialized socket using the UDP protocol.
Definition UdpSocket.hpp:50
Status bind(unsigned short port, IpAddress address=IpAddress::Any)
Bind the socket to a specific port.
Status receive(void *data, std::size_t size, std::size_t &received, std::optional< IpAddress > &remoteAddress, unsigned short &remotePort)
Receive raw data from a remote peer.
Status send(const void *data, std::size_t size, IpAddress remoteAddress, unsigned short remotePort)
Send raw data to a remote peer.
See also
sf::Socket, sf::TcpSocket, sf::Packet

Definition at line 49 of file UdpSocket.hpp.

Member Enumeration Documentation

◆ Status

enum class sf::Socket::Status
stronginherited

Status codes that may be returned by socket functions.

Enumerator
Done 

The socket has sent / received the data.

NotReady 

The socket is not ready to send / receive data yet.

Partial 

The socket sent a part of the data.

Disconnected 

The TCP socket has been disconnected.

Error 

An unexpected error happened.

Definition at line 48 of file Socket.hpp.

◆ Type

enum class sf::Socket::Type
strongprotectedinherited

Types of protocols that the socket can use.

Enumerator
Tcp 

TCP protocol.

Udp 

UDP protocol.

Definition at line 128 of file Socket.hpp.

Constructor & Destructor Documentation

◆ UdpSocket()

sf::UdpSocket::UdpSocket ( )

Default constructor.

Member Function Documentation

◆ bind()

Status sf::UdpSocket::bind ( unsigned short port,
IpAddress address = IpAddress::Any )
nodiscard

Bind the socket to a specific port.

Binding the socket to a port is necessary for being able to receive data on that port.

When providing sf::Socket::AnyPort as port, the listener will request an available port from the system. The chosen port can be retrieved by calling getLocalPort().

Since the socket can only be bound to a single port at any given moment, if it is already bound when this function is called, it will be unbound from the previous port before being bound to the new one.

Parameters
portPort to bind the socket to
addressAddress of the interface to bind to
Returns
Status code
See also
unbind, getLocalPort

◆ close()

void sf::Socket::close ( )
protectedinherited

Close the socket gracefully.

This function can only be accessed by derived classes.

◆ create() [1/2]

void sf::Socket::create ( )
protectedinherited

Create the internal representation of the socket.

This function can only be accessed by derived classes.

◆ create() [2/2]

void sf::Socket::create ( SocketHandle handle)
protectedinherited

Create the internal representation of the socket from a socket handle.

This function can only be accessed by derived classes.

Parameters
handleOS-specific handle of the socket to wrap

◆ getLocalPort()

unsigned short sf::UdpSocket::getLocalPort ( ) const
nodiscard

Get the port to which the socket is bound locally.

If the socket is not bound to a port, this function returns 0.

Returns
Port to which the socket is bound
See also
bind

◆ getNativeHandle()

SocketHandle sf::Socket::getNativeHandle ( ) const
nodiscardprotectedinherited

Return the internal handle of the socket.

The returned handle may be invalid if the socket was not created yet (or already destroyed). This function can only be accessed by derived classes.

Returns
The internal (OS-specific) handle of the socket

◆ isBlocking()

bool sf::Socket::isBlocking ( ) const
nodiscardinherited

Tell whether the socket is in blocking or non-blocking mode.

Returns
true if the socket is blocking, false otherwise
See also
setBlocking

◆ receive() [1/2]

Status sf::UdpSocket::receive ( Packet & packet,
std::optional< IpAddress > & remoteAddress,
unsigned short & remotePort )
nodiscard

Receive a formatted packet of data from a remote peer.

In blocking mode, this function will wait until the whole packet has been received.

Parameters
packetPacket to fill with the received data
remoteAddressAddress of the peer that sent the data
remotePortPort of the peer that sent the data
Returns
Status code
See also
send

◆ receive() [2/2]

Status sf::UdpSocket::receive ( void * data,
std::size_t size,
std::size_t & received,
std::optional< IpAddress > & remoteAddress,
unsigned short & remotePort )
nodiscard

Receive raw data from a remote peer.

In blocking mode, this function will wait until some bytes are actually received. Be careful to use a buffer which is large enough for the data that you intend to receive, if it is too small then an error will be returned and all the data will be lost.

Parameters
dataPointer to the array to fill with the received bytes
sizeMaximum number of bytes that can be received
receivedThis variable is filled with the actual number of bytes received
remoteAddressAddress of the peer that sent the data
remotePortPort of the peer that sent the data
Returns
Status code
See also
send

◆ send() [1/2]

Status sf::UdpSocket::send ( const void * data,
std::size_t size,
IpAddress remoteAddress,
unsigned short remotePort )
nodiscard

Send raw data to a remote peer.

Make sure that size is not greater than UdpSocket::MaxDatagramSize, otherwise this function will fail and no data will be sent.

Parameters
dataPointer to the sequence of bytes to send
sizeNumber of bytes to send
remoteAddressAddress of the receiver
remotePortPort of the receiver to send the data to
Returns
Status code
See also
receive

◆ send() [2/2]

Status sf::UdpSocket::send ( Packet & packet,
IpAddress remoteAddress,
unsigned short remotePort )
nodiscard

Send a formatted packet of data to a remote peer.

Make sure that the packet size is not greater than UdpSocket::MaxDatagramSize, otherwise this function will fail and no data will be sent.

Parameters
packetPacket to send
remoteAddressAddress of the receiver
remotePortPort of the receiver to send the data to
Returns
Status code
See also
receive

◆ setBlocking()

void sf::Socket::setBlocking ( bool blocking)
inherited

Set the blocking state of the socket.

In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking.

Parameters
blockingtrue to set the socket as blocking, false for non-blocking
See also
isBlocking

◆ unbind()

void sf::UdpSocket::unbind ( )

Unbind the socket from the local port to which it is bound.

The port that the socket was previously bound to is immediately made available to the operating system after this function is called. This means that a subsequent call to bind() will be able to re-bind the port if no other process has done so in the mean time. If the socket is not bound to a port, this function has no effect.

See also
bind

Member Data Documentation

◆ AnyPort

unsigned short sf::Socket::AnyPort {0}
staticconstexprinherited

Some special values used by sockets.

Special value that tells the system to pick any available port

Definition at line 62 of file Socket.hpp.

◆ MaxDatagramSize

std::size_t sf::UdpSocket::MaxDatagramSize {65507}
staticconstexpr

The maximum number of bytes that can be sent in a single UDP datagram.

Definition at line 56 of file UdpSocket.hpp.


The documentation for this class was generated from the following file: