-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·73 lines (51 loc) · 1.68 KB
/
server.py
File metadata and controls
executable file
·73 lines (51 loc) · 1.68 KB
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
68
69
70
71
72
73
#!/usr/bin/env python3
import socket
import sys
import select
import tty
import termios
import io
import pty
TRANSFER_CHUNK_SIZE = 2048
LISTEN_ADDR = '0.0.0.0'
LISTEN_PORT = 9999
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def main():
try:
sock = socket.socket() # actual conversation between server and client
except socket.error as msg:
eprint("Error creating socket: " + str(msg))
raise msg
try:
eprint("Binding socket to port: " + str(LISTEN_PORT))
sock.bind((LISTEN_ADDR, LISTEN_PORT))
sock.listen(5)
except socket.error as msg:
eprint("Error binding socket to port: " + str(msg))
raise msg
conn, address = sock.accept()
eprint("Connection has been established | " + "IP " + address[0] + " | Port " + str(address[1]))
old_tty = termios.tcgetattr(sys.stdin)
sys.stdin.close()
sys.stdout.close()
# Reopen STDIN and STDOUT in raw unbuffered mode.
# This allow as to read from stdin without blocking after select.
stdin = io.open(pty.STDIN_FILENO, 'rb', buffering=0)
stdout = io.open(pty.STDOUT_FILENO, 'wb', buffering=0)
try:
tty.setraw(stdin.fileno())
tty.setcbreak(stdin.fileno())
while True:
r, w, e = select.select([conn, stdin], [], [])
if stdin in r:
byte = stdin.read(TRANSFER_CHUNK_SIZE)
conn.send(byte)
if conn in r:
recv_data = conn.recv(TRANSFER_CHUNK_SIZE)
stdout.write(recv_data)
finally:
conn.close()
termios.tcsetattr(stdin, termios.TCSADRAIN, old_tty)
if __name__ == "__main__":
main()