On 1 Sep 2005 09:36:48 -0700, "n00m" <
[email protected]> declaimed the
following in comp.lang.python:
<something completely snipped>
I'm going to go back a few messages... Looking for a
simplification...
=====> ORIGINAL CODE
import socket, thread
host, port = '127.0.0.1', 1434
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2.connect((host, 1433))
s1.bind((host, port))
s1.listen(1)
cn, addr = s1.accept()
def VB_SCRIPT():
while 1:
data = cn.recv(4096)
if not data: return
s2.send(data)
print 'VB_SCRIPT:' + data + '\n\n'
def SQL_SERVER():
while 1:
data = s2.recv(4096)
if not data: return
cn.send(data)
print 'SQL_SERVER:' + data + '\n\n'
thread.start_new_thread(VB_SCRIPT,())
thread.start_new_thread(SQL_SERVER,())
TWO threads, both just infinite loops of the same nature (you could
actually have done ONE def and passed different arguments in to
differentiate the two thread invocations.
However, threads aren't really needed for this simple connection
relay... The following has /not/ been run (since I don't have your
server nor VBS) but should do about the same thing (see comments for one
lack).
=======> Suggested code
import socket
import select
host = "127.0.0.1"
DBMSPort = 1433
MyPort = 1434
MySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
DBMSSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
DBMSSocket.connect((host, DBMSPort))
MySocket.bind((host, MyPort))
MySocket.listen(1)
Client, Addr = MySocket.accept()
while True:
# wait for either connection to have readable data
(inbound, outbound, excption) = select.select([DBMSSocket, Client],
[], [])
# handle each readable socket
# NOTE: there is no way (in this quick and dirty code) to
# detect end of connections.
# probably need to do things with the excption list --
# passing in the sockets, and closing them when they
# show up in excption -- actually, if one side closes
# there is no reason to continue processing the other
# side, so on any excption, could close both and exit
for s in inbound:
data = s.recv(4096)
if s is Client:
print "From VBS: ",
MyDBMS.send(data)
elif s is MyDBMS:
print "From DBMS: ",
Client.send(data)
else:
print "\n\n*** ERROR: select() socket is not known!\n\n"
print repr(data)
print "\n"
--