-
Notifications
You must be signed in to change notification settings - Fork 26
/
python_socket.py
executable file
·67 lines (61 loc) · 1.68 KB
/
python_socket.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
62
63
64
65
66
67
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import StringIO
import contextlib
import traceback
import sys
import re
from sys import argv
script, PORT, token_file, sep = argv
##### set up a server
HOST = 'localhost'
PORT = int(PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Socket created
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# the SO_REUSEADDR flag tells the kernel to reuse a local socket in TIME_WAIT state,
# without waiting for its natural timeout to expire.
# see: https://docs.python.org/2/library/socket.html
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + '; Message: ' + msg[1]
quit()
s.listen(10) # Socket now listening
@contextlib.contextmanager
def stdoutIO(stdout=None):
'''
store outputs from stdout
'''
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
####### now keep talking with the client
while 1:
### wait to accept a connection
conn, addr = s.accept() # Connected with + addr[0] + str(addr[1])
input_data = conn.recv(1024000)
if re.sub('\s', '', input_data) == 'quit()':
break
### write the codes into a file
with open(token_file, 'w') as f:
f.write(input_data)
### print codes; execute codes
with stdoutIO() as output:
print input_data
print sep
try:
execfile(token_file)
except:
traceback.print_exc()
### send output
output_data = output.getvalue()
conn.send(output_data)
conn.close()
###### clsoe & quit
conn.close()
s.shutdown(2)
s.close()