UDP (datagram) socket usage.

Dar Scott dsc at swcp.com
Sun Dec 26 20:45:54 EST 2004


I have use the crossing pair before.  This is handy in some 
environments for symmetry in both TCP and UDP.  You usually can get 
symmetry with UDP without the crossed pair, but Revolution doesn't 
support that, the best I can tell.

On Dec 26, 2004, at 5:13 PM, Alex Tweedly wrote:

> Server pseudo-code:
>
>>     accept datagram connections on port "4567" with message 
>> "gotPacket"
>
>> on gotPacket pRemote, pData
>>   put pRemote into pRemote
>>   set the itemDel to ":"
>>   add 1 to item 2 of pRemote

There is a potential problem here.  The socket designator might include 
a socket ID.

>>   open datagram socket to pRemote
>>   write "reply with " & param(2) to socket pRemote
>>   close socket pRemote
>>   end gotPacket
>
> Now the echo client version, using standard system calls, is simply
>
>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>> r = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>
>> s.connect( (HOST,PORT) )
>>
>> # get the source port allocated, and listen on adjacent one
>> reply_host, reply_port = s.getsockname()
>> reply_port += 1
>> r.bind( (reply_host, reply_port) )
>>
>> while 1 :
>>     str = raw_input('type it')
>>     s.send(str)
>>     data = r.recv(1024)
>>     print "Back came ", data
>>     s.close()
>
> Most of this translates simply into Rev - except I can't find the 
> equivalent of  getsockname(), which tells me the local IP address and 
> port number which will be filled in as source addr, source port in the 
> UDP packet.

A weakness, in my opinion.

But you can work around this.

> The server uses this to determine where to send its reply; source addr 
> is, of course, just the IP address of the client machine (which I can 
> get from hostAddress() once I have connected the socket) - but I don't 
> see a way to find which source port will be chosen. Without that, I 
> don't know which port to bind to in order to receive the server 
> responses.
>
> Is there a way to find that ?

shell()?

> Or, alternatively, is there a different way to set up a client-server 
> UDP pair ?  i.e. have a pre-defined port number used on the server, 
> which is also configured in every client, but allocate the client 
> ports dynamically.

If you must have the crossing pair, simply send data to the 
corresponding port on the other side.  Both sides will have source 
ports that are not known, but the destination ports will be known.

But you don't need to use a crossing pair for a client server 
relationship.

The server knows the port on the other end (pRemote, in your example).  
Simply reply to that.

>
**********************************************
     DSC (Dar Scott Consulting & Dar's Lab)
     http://www.swcp.com/dsc/
     Programming Services and Software
**********************************************



More information about the use-livecode mailing list