forked from simon3270/ginlong-python
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathginserv_tcp.py
61 lines (51 loc) · 1.5 KB
/
ginserv_tcp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python3
# Initial Python 3 version
# Fails on encode line (but still runs on Python 2)
import socket
import time
import sys
HOST = ''
PORT = 5432
max_bind_count = 20
get_try_count = 45
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
sys.stdout.flush()
#Bind socket to local host and port
bind_count = 0
while bind_count < max_bind_count:
try:
s.bind((HOST, PORT))
break
except socket.error as msg:
print(time.strftime("%c ") + 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.stdout.flush()
time.sleep(10.0)
bind_count += 1
if bind_count == max_bind_count:
print(time.strftime("%c ") + 'Too many bind failures - exiting script')
sys.exit()
print('Socket bind complete')
sys.stdout.flush()
#Start listening on socket
s.listen(10)
print(time.strftime("%c ") + 'Socket now listening')
sys.stdout.flush()
# Now keep talking with the client but stop after a given number of goes
# (something hangs after 600-odd)
conn_count = 0
while conn_count < get_try_count:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print('Connected with ' + addr[0] + ':' + str(addr[1]))
buf = conn.recv(1024)
print(time.strftime("%c %s "))
# Python 2
# print(str(':'.join(b.encode('hex') for b in buf)))
# Python 3
print("".join(":{:02x}".format(x) for x in buf)[1:])
sys.stdout.flush()
conn = None
addr = None
conn_count += 1
s.close()