Code: Select all
; udp_client.pb
EnableExplicit
InitNetwork()
Define connectionID.i
Define lenSendLine.i
Define sendLine.s
Define result.i
OpenConsole()
connectionID = OpenNetworkConnection("127.0.0.1", 9000, #PB_Network_UDP)
PrintN("UDP Networking, type 'q<enter>' to exit")
; input a line of data, or 'q' to quit
Repeat
sendLine = Input()
If sendLine = "q"
Break
Else
lenSendLine = Len(sendLine)
If lenSendLine
SendNetworkData(connectionID, @sendLine, lenSendLine)
EndIf
EndIf
ForEver
; no close socket is needed!
CloseConsole()
End
Code: Select all
; udp_server.pb
EnableExplicit
; procedure to receive UDP data
Procedure ProcessRequest(clientNumber)
Protected result.i
Protected *memoryLocation
Protected memLength.i = 2048
*memoryLocation = AllocateMemory(memLength)
result = ReceiveNetworkData(clientNumber, *memoryLocation, memLength)
; in theory, there are no socket errors with UDP
PrintN("Client " + Str(clientNumber) + " received " + Str(result) + " bytes: " + PeekS(*memoryLocation, result))
FreeMemory(*memoryLocation)
EndProcedure
Define NSEvent.i
Define thisClient.i
Define keyPressed.s
Define serverNumber.i
Define portNumber.i = 9000
; initialize the network and create the server needed
InitNetwork()
serverNumber = CreateNetworkServer(#PB_Any, portNumber, #PB_Network_UDP)
OpenConsole()
PrintN("Started UDP Network Server on port " + Str(portNumber))
PrintN("Press Escape to exit")
PrintN("")
Repeat
NSEvent = NetworkServerEvent() ; if we receive data, it will be indicated here
Select NSEvent
Case #PB_NetworkEvent_Data ; raw data has been received
thisClient = EventClient() ; get the event client identifier
CreateThread(@ProcessRequest(), thisClient); threaded procedure to process incoming data
Default ; some other server event, or no event occurred
Delay(50) ; sleep so we don't hammer the processor
EndSelect
keyPressed = Inkey()
Until keyPressed = #ESC$
PrintN("Escape pressed, press <enter> to terminate this process")
CloseNetworkServer(serverNumber)
Input()
CloseConsole()
End