UDP Peer to Peer on a single PC
Posted: Sun Mar 02, 2008 3:28 pm
Disclaimer: Dare made me do it, if it doesn't work blame him!
This is a simple (not thread or anything else safe) UDP peer (or in PB terms UDP Client/Server). Its port usage is a little odd as it's designed to run on the one PC. Compile it to exe then run it twice. It should run once listening on 7001 with a partner of 7002 and then the second time you run it it will be the other way around.
if you want to use your broadcast address ( http://en.wikipedia.org/wiki/Broadcast_address ) then you will need more than one PC so you can listen on the same port on different IP's then just change the IP below from 127.0.0.1 to your broadcast address.

This is a simple (not thread or anything else safe) UDP peer (or in PB terms UDP Client/Server). Its port usage is a little odd as it's designed to run on the one PC. Compile it to exe then run it twice. It should run once listening on 7001 with a partner of 7002 and then the second time you run it it will be the other way around.
if you want to use your broadcast address ( http://en.wikipedia.org/wiki/Broadcast_address ) then you will need more than one PC so you can listen on the same port on different IP's then just change the IP below from 127.0.0.1 to your broadcast address.
Code: Select all
If InitNetwork() = 0
MessageRequester("Error", "Can't initialize the network !", 0)
End
EndIf
Declare UDPListen(Dummy.l)
Port1 = 7001
Port2 = 7002
CID = CreateNetworkServer(#PB_Any, Port1, #PB_Network_UDP)
If cid = 0
CID = CreateNetworkServer(#PB_Any, Port2, #PB_Network_UDP)
MyPort = Port2
PartnerPort = Port1
Else
MyPort = Port1
PartnerPort = Port2
EndIf
If CId = 0
MessageRequester("Error", "Ports in use", 0)
End
EndIf
;=============================================================
OpenConsole()
PrintN("Listening on: " + Str(MyPort))
CreateThread(@UDPListen(),0)
While 1
PrintN("Type Data to send: ")
SendData.s = Input()
ConnectionID = OpenNetworkConnection("127.0.0.1", PartnerPort, #PB_Network_UDP)
SendNetworkString(ConnectionID, SendData)
CloseNetworkConnection(ConnectionID)
Wend
CloseConsole()
;=============================================================
Procedure UDPListen(Dummy.l)
bufferlen = 1024
While 1
EventType = NetworkServerEvent()
If EventType = #PB_NetworkEvent_Data
*DataBuffer = AllocateMemory(bufferlen)
Result = ReceiveNetworkData(EventClient(), *DataBuffer, bufferlen)
PrintN("Data From: " + IPString(GetClientIP(EventClient())))
;Debug "bytes " + Str(result)
PrintN("Data: " + PeekS(*DataBuffer))
PrintN("")
PrintN("Type Data to send: ")
FreeMemory(*DataBuffer)
EndIf
Delay(50)
Wend
EndProcedure