-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_socket_recv.py
executable file
·52 lines (42 loc) · 1.53 KB
/
server_socket_recv.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
#!/usr/bin/env python3
"""
Socket Server.
Now receive line-based instruction. e.g.:
'1\n'
'2\n'
Will listen to port such as '9999'
"""
import os, sys
import socketserver
#import keyboardplay
class MyTCPInfoHandler(socketserver.StreamRequestHandler):
timeout = None;
# Override
def handle(self):
while True:
self.data = self.rfile.readline() # DO NOT REMOVE '\n'
print("Data is {}.".format(self.data))
if self.data == b'': # Connection reset by peer
print('Connection reset by peer.')
return
self.data = self.data.strip(b'\n') # REMOVE '\n'
if self.data == b'': # Empty Line
continue
if self.data == b'\x1b': # ESC
break
print("From {0}, Received: '{1}'.".format(self.client_address, self.data))
try:
mydata = self.data.decode('UTF-8') # 1-8
except UnicodeDecodeError: # Not valid unicode(utf-8) input
continue
# Now begin the handling
print('Connection closed by me.')
return
if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 9999
# Create server and Bind to port
server = socketserver.TCPServer((HOST, PORT), MyTCPInfoHandler)
# Activate it. Use CTRL+C to interrupt
server.serve_forever()
pass
# vim: set ts=8 sw=4 tw=0 et :