Class
UDPSocket
Description
Used for UDP (User Datagram Protocol) communications.
Properties
Name |
Type |
Read-Only |
Shared |
---|---|---|---|
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
Methods
Name |
Parameters |
Returns |
Shared |
---|---|---|---|
Group As String |
|||
Group As String |
|||
[Encoding As TextEncoding] |
|||
Data As Datagram |
Events
Name |
Parameters |
Returns |
---|---|---|
e As RuntimeException |
||
UserAborted As Boolean |
Property descriptions
UDPSocket.BroadcastAddress
BroadcastAddress As String
The machine's broadcast address.
This property is read-only.
You can specify this address when you call the Write method and the data will be broadcast across the network, but you will not receive the data you sent back.
This example uses the BroadcastAddress to get the address of the group.
EasyUDPSocket1.Write(EasyUDPSocket1.BroadcastAddress, "Hello World")
UDPSocket.Handle
Handle As Integer
This is the socket's internal descriptor and it can be used with Declare statements.
This property is read-only.
On Windows, Handle is a Socket, suitable for use in Declares on Windows.
On macOS and Linux, Handle is a UNIX socket descriptor.
The descriptor is platform-specific. If Handle is less than zero, the descriptor is not available.
UDPSocket.IsConnected
IsConnected As Boolean
Indicates whether the socket is currently connected.
This property is read-only.
For TCPSockets, a connection means you can send and receive data and are connected to a remote machine. For UDPSocket, this means that you are bound to the port and are able to send, receive, join or leave multicast groups, or set socket options.
If EasyUDPSocket1.IsConnected Then
// proceed using the connection
Else
MessageBox("Connection failed!")
End If
UDPSocket.LocalAddress
LocalAddress As String
The local IP address of the computer.
This property is read-only.
Var localIP As String = Socket1.LocalAddress
UDPSocket.NetworkInterface
NetworkInterface As NetworkInterface
Specifies which network interface the socket should use when binding.
You can get the network interface(s) of the user's computer by calling the GetNetworkInterface method of the System module.
Leaving this property set to Nil will use the currently selected interface. In the case of UDPSocket, if you assign a non-Nil value, the socket may not be able to receive broadcast messages. The behavior is OS-dependent; it appears to work on Windows but not on other supported operating systems. If you wish to send broadcast packets out, then you should not bind to a specific interface because the behavior is undefined.
This example specifies that the TCPSocket will use the first Network Interface on the user's computer.
TCPSocket1.NetworkInterface = System.NetworkInterface(0)
UDPSocket.PacketsAvailable
PacketsAvailable As Integer
The number of packets available in the internal receive buffer.
This property is read-only.
UDPSocket.PacketsLeftToSend
PacketsLeftToSend As Integer
The number of packets left in the queue to send.
This property is read-only.
This enables you to create a synchronous socket without needing to subclass the UDPSocket.
UDPSocket.Port
Port As Integer
The port to bind on or connect to.
On most operating systems, attempting to bind to a port less than 1024 causes a Error event to fire with an error number 107 unless the application is running with administrative permissions. This is due to security features built into the underlying OS.
You need to set the port property explicitly before any call to Listen or Connect as the Port property will be modified to reflect what the actual bound port is during the various stages of operation.
For instance, if you listen on port 8080 and a connection comes in, you can check the Port property to ensure that you're still listening on port 8080 (that the port hasn't been hijacked). Or, if you connect to a socket on port 8080, once the connection occurs, you can check to see what port the OS has bound you to. This will be a random-seeming port number.
This trick can be very useful when you do things like Listen on port 0. In that case, the OS will pick a port for you and listen on it. Then you can check the Port property to see which port the OS picked. This functionality is used for various protocols, such as FTP.
This example sets the Port to 8080.
TCPSocket1.Port = 8080
UDPSocket.RouterHops
RouterHops As Integer
Specifies how many router hops the data sent out can make.
Multicasting has some extra features that make it an even more powerful utility for network applications. If you wish to receive the data you sent out with a multicast send, you can set the SendToSelf property (also known as loopback) of the UDPSocket. If it is set to True, then when you do a send (to a multicast group) you will get that data back. You can also set the number of router hops a multicast datagram will take (This is also known as the Time To Live (or TTL). When your Datagram gets sent out, it runs through a series of routers on the way to its destinations. Every time the Datagram hits a router, its RouterHops property gets decremented. When that number reaches zero, the Datagram is destroyed. This means you can control who gets your datagrams with a lot more precision. There are some “best guesses” as to what the value of RouterHops should be.
Value |
Description |
---|---|
0 |
Same host |
1 |
Same subnet |
32 |
Same site |
64 |
Same region |
128 |
Same continent |
255 |
Unrestricted |
Note that if your Datagram runs through a router that does not support multicasting, it is killed immediately.
EasyUDPSocket1.RouterHops = 32
UDPSocket.SendToSelf
SendToSelf As Boolean
Specifies whether the data you send out will be sent to yourself as well.
This is also known as loopback. This property applies only to multicast sends.
Setting the SendToSelf property to True may not work on all versions of Windows. MSDN states that the SendToSelf property on NT 4 cannot be turned off. A multicasting socket will always receive the data it sends out.
EasyUDPSocket1.SendToSelf = True
Method descriptions
UDPSocket.Close
Close
Closes the socket's connection, closes any connections the socket may have, and resets the socket.
The only information that is retained after calling Close is the socket's port, address (in the case of TCPSockets), LastErrorCode properties, and data left in the socket's receive buffer. All other information is discarded.
This example closes the EasyTCPSockets that were open. The sockets were added to the main window.
Connector.Close
Listener.Close
UDPSocket.Connect
Connect
Attempts to connect.
For TCPSockets, the address and port properties must be set. For UDPSocket, the port property must be set. The Connect method binds a socket to a port. After calling Connect, the Port property will report the actual port you are bound to.
UDPSocket.JoinMulticastGroup
JoinMulticastGroup(Group As String) As Boolean
Joins the specified multicast group. Returns True if the group was successfully joined, False if not.
If EasyUDPSocket1.JoinMulticastGroup(TextField5.Text) Then
MessageBox("Joined!")
End If
UDPSocket.LeaveMulticastGroup
LeaveMulticastGroup(Group As String)
Leaves the specified multicast group. The TextField contains the name of the group.
EasyUDPSocket1.LeaveMulticastGroup(TextField5.Text)
UDPSocket.Poll
Poll
Polls the socket manually, which allows a socket to be used synchronously.
The EasyTCPSocket "Listener" has been added to the window.
Listener.Poll
UDPSocket.Purge
Purge
Removes all data from the socket's internal receive buffer. It does not affect the socket's internal send buffer.
Listener.Purge
UDPSocket.Read
Read([Encoding As TextEncoding]) As Datagram
Returns a Datagram from the internal receive buffer.
The address property of the Datagram is the remote address from which the data was sent. The optional Encoding parameter enables you to specify the text encoding of the data to be returned. Use the Encodings module to specify a text encoding.
UDPSocket.Write
Write(Address As String, Data As String)
Constructs a Datagram and sends the data to the specified address.
UDPSocket.Write
Write(Data As Datagram)
Constructs a Datagram and sends the data to the specified address.
This example uses BroadcastAddress to get the address of the group.
UDPSocket1.Write(UDPSocket1.BroadcastAddress, "Hello World")
Event descriptions
UDPSocket.DataAvailable
DataAvailable
Occurs when additional data has come into the internal receive buffer.
UDPSocket.Error
Error(e As RuntimeException)
Occurs when an error occurs with the socket.
These error codes provide you with key information about your socket, and it is not advisable to ignore them.
When an error occurs, the RuntimeException.ErrorNumber property will likely contain one of the following error codes:
Error Code |
Description |
---|---|
0 |
No error occurred. |
100 |
There was an error opening and initializing the drivers. |
101 |
This error code is no longer used. |
102 |
This code means that you lost your connection. |
103 |
The socket was unable to resolve the address that was specified. |
104 |
This error code is no longer used. |
105 |
The address is currently in use. |
106 |
This is an invalid state error, which means that the socket is not in the proper state to be doing a certain operation. |
107 |
This error means that the port you specified is invalid. |
108 |
This error indicates that your application has run out of memory. |
These are not the only errors that are returned. For Windows, additional error codes are usually positive numbers in the range [10004, 11004]. For Windows error codes, see WinSock.h. MacOS and Linux use POSIX error codes. For a description of macOS and Linux error codes, see http://www.ioplex.com/~miallen/errcmp.html.
e.g. error 64 is for "host is down".
The following example in the Error event handler displays the error code.
MessageBox(Me.e.ErrorNumber.ToString)
UDPSocket.SendComplete
SendComplete(UserAborted As Boolean)
Occurs when a send has completed.
Use this to determine when all your data has been sent. UserAborted will be True if the user aborted the send by returning True from the SendProgress event. You can use this information to update different status variables or to inform user about the success or failure of the transfer. If the send was completed, this value is False. UserAborted will always be False for UDP sockets.
Notes
You do not need to add a UDPSocket control to a window in order to use it. Since it is not a subclass of Control, you can instantiate it via code.
The User Datagram Protocol, or UDP, is the basis for most high speed, highly distributed network traffic. It is a connectionless protocol that has very low overhead, but is not as secure as TCP. Since there is no connection, you do not need to take nearly as many steps to prepare when you wish to use a UDPSocket.
In order to use a UDPSocket, it must be bound to a specific port on your machine. This is done using the Connect method of the SocketCore class. Once the bind has occurred, the UDPSocket is ready for use. It will immediately begin accepting any data that it sees on the port it has bound to. It also allows you to send data out, as well as set UDP socket options (which will be described later).
In order to differentiate between which machine is sending you what data, a UDPSocket uses a data structure known as a Datagram. A Datagram consists of two parts, the IP address of the remote machine that sent you the data, and the payload - or the actual data itself. When you attempt to send data out, you must specify information in the form of a Datagram. This information is usually the remote address of the machine you want to receive your packet, the port it should be sent to, and the data you wish to send the remote machine.
UDP sockets can operate in various modes, which are all very similar, but have vastly different uses. The mode that most resembles a TCP communication is called "unicasting." This occurs when the IP address you specify when you write data out is that of a single machine. An example would be sending data to www.example.com, or some other network address. It is a Datagram that has one intended receiver.
The second mode of operation is called "broadcasting." As the name implies, this is a broadcasted write. It is akin to yelling into a megaphone. Everyone gets the message, whether they want to or not. If the machine happens to be listening on the specific port you specified, then it will receive the data on that port. This type of send is very network intensive. As you can imagine, broadcasting can amount to huge amount of network traffic. The good news is, when you broadcast data out, it does not leave your subnet. Basically, a broadcast send will not leave your network to travel out into the world. When you want to broadcast data, instead of sending the data to an IP address of a remote machine, you specify the broadcast address for your machine. This address changes from machine to machine, so use the BroadcastAddress property of the UDPSocket class which tells you the correct broadcast address.
The third mode of operation for UDP sockets is "multicasting." It is a combination of unicasting and broadcasting that is very powerful and practical. Multicasting is a lot like a chat room: you enter the chatroom, and are able to hold conversations with everyone else in the chatroom. When you want to enter the chatroom, you call JoinMulticastGroup, and you only need to specify the group you wish to join. The group parameter is a special kind of IP address, called a Class D IP. They range from 224.0.0.0 to 239.255.255.255. Think of the IP address as the name of the chatroom. If you want to start chatting with two other people, all three of you need to call JoinMulticastGroup with the same Class D IP address specified as the group. When you wish to leave the chatroom, you only need to call LeaveMulticastGroup, and again, specify the group you wish to leave. You can join as many multicast groups as you like, you are not limited to just one at a time. When you wish to send data to the multicast group, you only need to specify the multicast group's IP address. All people who have joined the same group as you will receive the message.
Multicasting has some extra features that make it an even more powerful utility for network applications. If you wish to receive the data you sent out with a multicast send, you can set the SendToSelf property (also known as loopback) of the UDPSocket. If it is set to True, then when you do a send (to a multicast group) you will get that data back. You can also set the number of router hops a multicast datagram will take (also known as the Time to Live). When your Datagram gets sent out, it runs through a series of routers on the way to its destinations. Every time the Datagram hits a router, its RouterHops property gets decremented. When that number reaches zero, the Datagram is destroyed. This means you can control who gets your datagrams with a lot more precision. There are some "best guesses" as to what the value of RouterHops should be.
Value |
Description |
---|---|
0 |
Same host |
1 |
Same subnet |
32 |
Same site |
64 |
Same region |
128 |
Same continent |
255 |
Unrestricted |
Note that if your Datagram runs through a router that does not support multicasting, it is killed immediately.
Due to the connectionless functionality of UDP, it does not make any guarantees that your data will reach its destination. You can work around this by creating your own protocol on top of the UDP protocol which acknowledges receives.
The UDPSocket operates in asynchronous mode, but the Connect method works synchronously. If the connect fails, you will get an error event immediately, and the IsConnected property will be set immediately.
Xojo cloud
Web apps running on Xojo Cloud first have to use the FirewallPort class to open the port used to permit external or internal connections to UDP.
Compatibility
All project types on all supported operating systems.
See also
SocketCore parent class; Datagram, EasyUDPSocket, SocketCore classes.