#Script collection demonstrating UDP socket communication in Scorpion.
Central Start:
import socket
receivedFromAddress = None # will be set when receiving data
receivePort = 1501 # listen on this port
sendToAddress = (sendToIPAddress, sendToPort) # target for sending data
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
udp.bind(('', receivePort))
udp.settimeout(0.01)
Central Stop:
udp = None
# to be called at short intervals from a timer
# ensure no time-consuming tasks are done inside this function.
def Receive():
global udp
global receivedFromAddress
if udp == None:
print 'no udp object'
return
bufsize = 16384
try:
data, receivedFromAddress = udp.recvfrom(bufsize)
except socket.timeout:
return # no data waiting in buffer
except Exception, err:
print 'recv exception:', err
return
print 'Received %d bytes from' % len(data), receivedFromAddress
#use the data string
def Send(data):
global udp
sendToIPAddress = '127.0.0.1'
sendToPort = 1500
sendToAddress = (sendToIPAddress, sendToPort)
if udp <> None:
try:
udp.sendto(data, sendToAddress)
except Exception, err:
print 'Send exception: ', err
return
else:
print 'Send: No socket object'
|