User Tools

Site Tools


Sidebar

Network and communication

k24:k24.1:k24.1.3:start

24.1.3.0 Class UDPSocket (gb.net)

The UDPSocket (gb.net) class allows Gambas programmes to communicate via UDP sockets. The class inherits from the Stream class, so you can use standard stream methods to read, write and close the socket.

24.1.3.0.1 Notes on the UDP protocol

In contrast to the TCP protocol, the UDP protocol (User Datagram Protocol) works connectionless. This means that there is no network connection with controlled data flow between two programmes with UDP sockets. Therefore, you will not find the two methods Listen() and Accept() with UDP sockets. There is also no confirmation whether the data - so-called datagrams - have arrived at the communication partner. Only datagrams are sent or received. This is not the only reason why the UDP protocol is considered an insecure protocol.

Good to know:

  • The class can be used as a server or as a client, since each datagram sent or received is identified by its host IP and port.
  • With a Unix socket, the host IP and the port of the communication partner to be used must be known before a datagram can be sent.
  • For example, if a UDP socket has been created and initialised for a server, you can start sending datagrams immediately. Initialisation consists of the server binding itself to a port that must also be known to the clients!
  • With the help of a broadcast in the subnet, a client can inquire which communication partners are still on the way on the client's port. To do this, you need the broadcast IP address for the subnet and must set the property UDPSocket.Broadcast to True, otherwise an error will be triggered. If a communication partner - for example a server - responds, you can read its IP address from its response and start the communication.
  • Unlike a TCP socket, a UDP socket is not bound to a single communication partner!

The last listed points are implemented in the following source code fragments for a UDP server and a UDP client:

UDP server:

Public UDPServerSocket As UDPSocket
 
'-- Es wird ein UDP-Socket erzeugt ▶ SERVER
    UDPServerSocket = New UDPSocket As "UDPServerSocket"
 
    If UDPServerSocket.Status <= Net.Inactive Then
       UDPServerSocket.Port = Val(txbPort.Text)
       UDPServerSocket.Bind()
    Endif
 
Public Sub UDPServerSocket_Read()
 
    Dim sBuffer, sQuote As String
 
    Read #UDPServerSocket, sBuffer, Lof(UDPServerSocket)
 
'-- Run Service: Ausgabe eines zufälligen Zitates → Methode GetQuote(…)
    sQuote = GetQuote(sBuffer)
 
'-- Ziel-Adressierung: Host und Port
'-- Über die Eigenschaften UDPServerSocket.SourceHost und UDPServerSocket.SourcePort findet man heraus,
'-- woher das Datagramm kam – wer der Absender war. Damit sind die Ziel-Informationen zum Senden komplett.
 
    UDPServerSocket.TargetHost = UDPServerSocket.SourceHost
    UDPServerSocket.TargetPort = UDPServerSocket.SourcePort
 
'-- Das Zitat wird als Datagramm an das adressierte Ziel gesendet
    Write #UDPServerSocket, Trim(sQuote), Len(Trim(sQuote))
 
End

UDP client:

Public UDPClientSocket As UDPSocket
 
'-- Es wird ein UDP-Socket erzeugt ▶ CLIENT
    UDPClientSocket = New UDPSocket As "UDPClientSocket"
 
    If UDPClientSocket.Status <= Net.Inactive Then
       UDPClientSocket.Port = 0 ' Standard-Port für einen UDP-Client
       UDPClientSocket.Bind()
    Endif
 
Public Sub SendDatagram()
 
'-- Ziel-Adressierung: Host und Port
    UDPClientSocket.TargetHost = txbHost.Text
    UDPClientSocket.TargetPort = txbPort.Text
 
    Inc Application.Busy
    '-- Ein Datagramm wird an das adressierte Ziel gesendet
        Write #UDPClientSocket, txbRequest.Text, Len(txbRequest.Text)
    Dec Application.Busy
 
End

24.1.3.0.2 Properties

The UDPSocket class has these properties:

PropertyData typeDescription
HostStringReturns or sets the IP address to which the UDP socket is bound.
SourceHostStringReturns the IP address of the source if the message comes from the Internet.
SourcePortIntegerReturns the port of the source if the message comes from the Internet.
SourcePathStringReturns the path of the source if the message comes from a local socket.
TargetHostStringDefines the IP address (destination) if the message goes to the Internet.
TargetPortIntegerDefines the port (destination) when the message goes to the Internet.
TargetPathStringDefines the path (destination) when the message goes to a local socket.
PathStringReturns the path of the local socket to connect to or sets the path.
PortIntegerReturns or sets the port number used to bind the UDP socket.
StatusIntegerReturns the status of the UDPSocket as a constant of the Net class → Chapter 24.x.y.
TimeoutIntegerReturns or sets the timeout in milliseconds.
BroadcastBooleanThis property sets or clears the socket broadcast flag.

Table 24.1.3.0.1 : Properties of the UDPSocket class.

Notes:

  • Port: The value must be a natural number between 0 and 65535. Port 0 is the usual port for UDP clients. 1 to 65535 binds a server socket to the specified port. Custom ports should be assigned in the range 49152 to 65535.
  • At https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers you will find an overview of assigned UDP port numbers.
  • Broadcast: If the property UDPSocket.Broadcast has the value True, UDP sockets datagrams can be sent to a broadcast address. Example: with a subnet IP address of 192.168.2 and the default subnet mask 255.255.255.0, the broadcast IP address is 192.168.2.255. More generally, the broadcast IP address would be 255.255.255.255.

24.1.3.0.3 Methods

The UDPSocket class has the following methods:

MethodReturnTypeDescription
Begin ( )-Begin buffering the data written to the stream in the socket buffer so that everything is sent when the Send method is called.
Close ()-Closes the UDP socket.
Send ( )-Sends all data buffered in the socket buffer since the last call of the Begin() method in one go.
Bind ( )-Binds a socket to a host or to a path so that the object can start sending and receiving data.
Drop ( )-Deletes all data buffered in the socket buffer since the last call to the Begin() method.
Peek ( )StringUse this function to receive data from the socket. It may only be used if the connection is active (status = Net.Connected), otherwise an error is triggered.
ReadLine ( [ Escape As String ] )StringReads a line of text from the data stream, like the one in the instruction LINE INPUT.
Watch ( Mode As Integer, Watch As Boolean )-Start or stop monitoring the stream file descriptor for reading or writing after it has been opened.

Table 24.1.3.0.2 : Methods of the UDPSocket class.

Notes:

  • Bind(): If Path is defined, then the socket is a local socket bound to it. Otherwise, the socket is an Internet socket bound to the port specified by the Port property. This function can only be used if the Status property is zero (inactive) or less than zero. Otherwise, an error is triggered.
  • Peek(): The string is not deleted from the socket buffer. So the next time you receive data as a datagram, you will receive the same string, supplemented by new data that has arrived in the UDP socket.
  • ReadLine(…): If an 'escape' character is specified, then line breaks between two escape characters are ignored. This method is very useful when reading CSV files.
  • Watch(): 'Mode' is the monitoring type: set gb.Read to watch when reading and gb.Write to watch when writing. Watch = True enables monitoring and Watch = False disables monitoring.

24.1.3.0.4 Events

The UDPSocket class only has these two events:

EventDescription
Error ( )This event occurs when instructions have failed. For example, when a binding attempt failed. The status property then has a negative value reflecting the error type. The UDP socket is automatically closed after an error!
Read ( )This event is triggered when data arrives in the socket from the communication partner on the other side of the IP connection.

Table 24.1.3.0.3 : Events of the class UDPSocket

Note on the Error() event: Knowing selected error constants can help you identify the reason for errors that occur:

  • Net.CannotCreateSocket (-2) The system did not allow a UDP socket to be created.
  • Net.CannotRead (-4) Error while trying to receive data.
  • Net.CannotWrite (-5) Error while trying to send data.
  • Net.CannotBindSocket (-10) The requested port could not be used (bound).
The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k24/k24.1/k24.1.3/start.txt · Last modified: 18.06.2022 (external edit)

Page Tools