Hi,
Unfortunately SocketConnect
doesn't yet support UDP sockets like you are describing. However, you can use J/Link
to create a DatagramSocket
Java object to accomplish the same thing. I have some example code below.
Needs["JLink`"];
InstallJava[];
udpSocket = JavaNew["java.net.DatagramSocket", 5000];
This creates a socket object that you can send and receive with using the methods receive
and send
. Both of these methods take a DatagramPacket
object as their arguments, which can be created with JavaNew
as below in the Module
.
readSocket[sock_, size_] :=
JavaBlock@
Block[
{datagramPacket = JavaNew["java.net.DatagramPacket", Table[0, size], size]},
sock@receive[datagramPacket];
datagramPacket@getData[]
]
To write a byte array to the socket, you can use the following function, which will use the provided socket to send data over UDP :
writeSocket[sock_, dest_String, port_Integer, data_ /; AllTrue[data, IntegerQ[#] && # >= 0 && # <= 255 &]] :=
JavaBlock@
sock@send[
JavaNew["java.net.DatagramPacket", data, Length[data], InetAddress`getByName[dest],port]
]
Here's an example of sending data to a socket and receiving it:
writeSocket[udpSocket, "127.0.0.1", 5000, ToCharacterCode["hello from mathematica"]]
Then read in the raw byte data:
readSocket[udpSocket, 40]
{104, 101, 108, 108, 111, 32, 102, 114, 111, 109, 32, 109, 97, 116,
104, 101, 109, 97, 116, 105, 99, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
This can be turned back into the original string with FromCharacterCode
:
DeleteCases[%, 0] // FromCharacterCode
"hello from mathematica"
I hope this helps, and I'd be delighted to hear more about your robot.
Thanks,
Ian