UDP socket example

230 views
Skip to first unread message

Eric Lendvai

unread,
Feb 12, 2021, 5:43:37 AM2/12/21
to Harbour Users
Does anyone have some example code on sending and listening to UDP packets/messages?

In Python this can be done with the following code:

//Listening Program
import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 49152

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    try:
        data, addr = sock.recvfrom(4000) # buffer size is 4000 bytes
        print(data.decode("utf-8") )
    except:
        print("Overflow")

//Transmitting program
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
address = ('127.0.0.1', 49152)
sock.sendto('Test Message', address)
sock.close()

I am using these from Python based PostgreSQL stored functions, but was hoping to use Harbour instead.

The main advantage of UDP versus TCP or file logging, is that if you don't listen to messages, no extra disk space is used and there is very little performance loss. That is also the way DebugView works by the way.


Bernard Mouille

unread,
Feb 12, 2021, 6:02:58 AM2/12/21
to Harbour Users
Hello Eric,
You have a sample :
\hb32\contrib\hbnetio\tests\netiot03.prg
Regards,
Bernard

Francesco Perillo

unread,
Feb 12, 2021, 6:06:16 AM2/12/21
to harbou...@googlegroups.com
I remember to have asked this question in the past, and Przemek answered with a sample. Many years ago.

--
--
You received this message because you are subscribed to the Google
Groups "Harbour Users" group.
Unsubscribe: harbour-user...@googlegroups.com
Web: http://groups.google.com/group/harbour-users

---
You received this message because you are subscribed to the Google Groups "Harbour Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to harbour-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/harbour-users/8b2d94ea-9088-4b20-8642-d15d4309d929n%40googlegroups.com.

Mario H. Sabado

unread,
Feb 12, 2021, 6:26:41 AM2/12/21
to 'elch' via Harbour Users
HI Eric,

Found this entry in the change log.

  * contrib/hbmisc/udpds.prg

Regards,
Mario


Eric Lendvai

unread,
Feb 13, 2021, 2:02:23 AM2/13/21
to Harbour Users
Thank you all for your suggestions!

I was able to simplify the code down to the following:

This will send 4000 messages.

#include "hbsocket.ch"

function Main()
local hSocket
local cIP   := "127.0.0.1"
local nPort := 49152
local cMessage := "Test"
local nLoop

if ! Empty(hSocket := hb_socketOpen(,HB_SOCKET_PT_DGRAM))
    for nLoop := 1 to 4000
        hb_socketSendTo(hSocket,cMessage+" "+AllTrim(str(nLoop)),,,{ HB_SOCKET_AF_INET,cIP, nPort })
        MyOutputDebugString("[Harbour] "+cMessage+" "+AllTrim(str(nLoop)))
    next
    hb_socketClose(hSocket)
endif

return nil

Reply all
Reply to author
Forward
0 new messages