FreeWRL/FreeX3D  3.0.0
zb.py
1 import socket
2 import sys
3 import threading
4 from threading import *
5 
6 HOST = 'localhost' # Symbolic name meaning all available interfaces
7 PORT = 8080 # Arbitrary non-privileged port
8 
9 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
10 print('Socket created')
11 
12 #Bind socket to local host and port
13 #try:
14 s.bind((HOST, PORT))
15 ##except socket.error , msg:
16 ## print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
17 ## sys.exit()
18 
19 print( 'Socket bind complete')
20 
21 #Start listening on socket
22 s.listen(10)
23 print( 'Socket now listening')
24 
25 
26 def forward_to_ssr(request):
27  HOST = 'localhost' # Symbolic name meaning all available interfaces
28  PORT = 8081 # Arbitrary non-privileged port
29 
30  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
31  s.connect((HOST, PORT))
32  #conn, addr = s.accept()
33  print( 'Connected with ' + addr[0] + ':' + str(addr[1]))
34  print('forwarding'+str(request))
35  #conn.send(request)
36  s.sendall(request)
37  response = Null
38  while True:
39  data = s.recv(16383) #conn.recv(16383)
40  if data:
41  response = data
42  if not data:
43  break
44  return response
45 
46 #Function for handling connections. This will be used to create threads
47 def clientthread(conn):
48  #Sending message to connected client
49  #conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
50 
51  #infinite loop so that function do not terminate and thread do not end.
52  reply = ''
53  request = None
54  while True:
55 
56  #Receiving from client
57  data = conn.recv(1024)
58  if data:
59  request = data
60  if not data:
61  break
62  reply = forward_to_ssr(request)
63  conn.sendall(reply)
64  #came out of loop
65  conn.close()
66 
67 #now keep talking with the client
68 while 1:
69  #wait to accept a connection - blocking call
70  conn, addr = s.accept()
71  print('Connected with ' + addr[0] + ':' + str(addr[1]))
72 
73  #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
74  t = threading.Thread(target=clientthread,args=(conn,))
75  t.start()
76 
77 s.close()