FreeWRL / FreeX3D 4.3.0
zb.py
1import socket
2import sys
3import threading
4from threading import *
5
6HOST = 'localhost' # Symbolic name meaning all available interfaces
7PORT = 8080 # Arbitrary non-privileged port
8
9s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
10print('Socket created')
11
12#Bind socket to local host and port
13#try:
14s.bind((HOST, PORT))
15
18
19print( 'Socket bind complete')
20
21#Start listening on socket
22s.listen(10)
23print( 'Socket now listening')
24
25
26def 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
47def 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
68while 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
77s.close()