If you want to implement TCP/IP communication using sockets, you can use
Python and the socket API. The socket API is a BSD
implementation and is well documented in the Python help system. Using
sockets, you have to decide if your Scorpion application is going
to be the server or the client. This example shows how you can be a server.
Example 31 shows a tcp/ip client.
Look in Central.Start for the initialization code which sets up the
serversocket. Then look in the script socktrig
for the code that checks if a request is inbound on the serversocket. If so,
a clientsocket is used for subsequent operation. If the client socket
is closed, a new incoming connection will be allowed. In this fashion the
client can connect and close without any protocol handshakes.
What should the client side code look like? In Python you can use this
script:
from socket import *
def Trigger():
ip='localhost'
port=9901
csock=socket(AF_INET,SOCK_STREAM)
csock.settimeout(1.0)
csock.connect( (ip,port) )
csock.send('PartPresent')
print csock.recv(100)
csock.close()
The example is contained in the example profile
SocketServer.zip. The example requires python 2.3 or higher
to be installed. Example : Socket Server - server side
Central Start
import sys
from socket import *
ip='localhost'
port=9901
ssock=socket(AF_INET,SOCK_STREAM)
ssock.settimeout(0.2)
ssock.bind ( (ip,port) )
ssock.listen(1)
csock=0
connected=0
tries=0
Central Stop
ssock.close()
SockTrig # called from scheduler
def socktrig():
import socket
global csock
global connected
if connected:
# socket is there
try:
msg=csock.recv(256)
if msg=='':
# socket closed
print 'Client disconnected'
csock.close()
csock=0
connected=0
elif msg==GetValue('Trigger.Text'): # contains PartPresent
print 'PartPresent'
ExecuteCmd('GrabExecute','')
else:
print 'Unknown command',msg
except socket.timeout:
pass #no data in buffer yet, no error condition
except:
try:
csock,addr=ssock.accept()
csock.settimeout(0.2)
print 'Client connected',addr
connected=1
except:
print 'Timeout waiting for connection'
else:
# accept new connection if not connected
try:
csock,addr=ssock.accept()
csock.settimeout(0.2)
print 'Client connected',addr
connected=1
except:
print 'Still waiting for connection'
Sending response # sends message in external tool
global csock
if connected:csock.send(GetValue('ResponsePass.Text'))
|