UDP example

BlitzMax Forums/BlitzMax Programming/UDP example

When I said 'raw sockets', I meant via the BMax sockets module as this makes things easier. I'm by no means an expert with sockets but they seem fairly straight forward, it could well be a case of 'ignorance is bliss' thought.

@Moogles - As you asked so nicely, here's simple example you may recognise... ;o)

Strict

Framework BRL.Basic
Import BRL.socket
Import BRL.standardio


Local socket:TSocket = CreateUDPSocket()

If socket = Null Then RuntimeError "Couldn't create UDP socket"

If ConnectSocket(socket, HostIp("83.149.87.203"), 7778) = False Then RuntimeError "Couldn't connect to server"

SWriteLine socket, "\info"

Print DottedIP(SocketRemoteIP(socket)) + " : " + SocketRemotePort(socket)
Print

Local info$ = SRead$(socket)

Print info.length + " : " + info$

socket.Close()

End


Function SRead$(socket:TSocket)
	Local buf:Byte[1024]
	Local receivedLen = socket.Recv(buf, 1024)
	
	Return String.FromBytes(buf, receivedLen)
End Function	

Function SWriteLine(socket:TSocket, str$)
	Local buf:Byte Ptr = (str$ + "~r~n").ToCString()
	Local sent = socket.Send(buf, str.length + 2)

	MemFree buf
	
	Return sent = (str.length + 2)
End Function

A more 'correct' way is probably something like...

Strict

Framework BRL.Basic
Import BRL.socket
Import BRL.standardio

Local socket:TSocket = CreateUDPSocket()

If socket = Null Then RuntimeError "Couldn't create UDP socket"

SWriteLine(socket, "83.149.87.203", 7778, "\info")

Local info$ = SRead$(socket, "83.149.87.203", 7778)

Print info.length + " : " + info$

socket.Close()

End


Function SRead$(socket:TSocket, host$, port, bufferSize=1024)
	Local buf:Byte[bufferSize], rip, rport  
	Local receivedLen, time = MilliSecs()
	
	Repeat
		receivedLen = 0
		Local read = socket._socket
		If socket.Connected()
			Local size = socket.ReadAvail()
			If size
				receivedLen = recvfrom_(socket._socket, buf, size, 0, rip, rport)
				If (rip = HostIp(host$)) And (rport = port) Then Exit
			EndIf
		EndIf	
	Until (MilliSecs() - time) >= 30000
	
	If receivedLen > 0 Then Return String.FromBytes(buf, receivedLen)
End Function	

Function SWriteLine(socket:TSocket, host$, port, str$)
	Local buf:Byte Ptr = (str$ + "~r~n").ToCString()
	Local sent = sendto_(socket._socket, buf, str.length + 2, 0, HostIp(host$), port)

	MemFree buf
	
	Return sent
End Function


If you're only going to be doing simple stuff, like above, the network libraries are overkill IMHO. If, however, you're going to be doing anything mildly useful then use one of the libraries (I haven't used BNet myself, but it seems to be very highly rated by those that have).