Socket Programing

BlitzMax Forums/BlitzMax Programming/Socket Programing

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

Here's a very thin layer over the low-level socket functions for writing TCP clients:
Function Connect(server$, port)
	Local addr_type, addr_len
	Local addrs:Byte Ptr Ptr = gethostbyname_(server, addr_type, addr_len)
	If addrs = Byte Ptr Ptr(0) Return 
	If addr_type <> AF_INET_ Return -1
	
	Local sock = socket_(addr_type, SOCK_STREAM_, 0)
	If sock < 0 Return sock
	
	If connect_(sock,addrs[0], addr_type, addr_len, port) < 0
		closesocket_ sock
		Return -1
	EndIf

	Return sock
End Function

Function ReadSocket(socket, buf:Byte Ptr, count)
	Return recv_(socket, buf, count, 0) 
End Function

Function WriteSocket(socket, buf:Byte Ptr, count)
	Return send_(socket, buf, count, 0)
End Function

Function CloseSocket(socket)
	If socket closesocket_(socket)
End Function
You open a socket like this:
Global Socket = Connect("localhost", Port)

If Socket < 0 Then
	Print "Didn't work."
	CloseSocket(Socket)
	End
EndIf
Once the socket is open, you read from it with ReadSocket. That function waits until either data is received or the socket is closed.

You can also use TSocketStream and do this in essentially one line, but I like seeing what's going on behind the scenes in this case.

Hope this helps!