-
Notifications
You must be signed in to change notification settings - Fork 0
/
echoser.py
93 lines (63 loc) · 2.04 KB
/
echoser.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import socket
import os
import argparse
import sys
import datetime
import logging
# logger conf
logging.basicConfig(level = logging.DEBUG,
format = "%(asctime)s %(levelname)-5s --- %(message)s",
stream = sys.stdout,
datefmt = "%d-%m-%Y %H:%M" )
logger = logging.getLogger("eser")
logger.setLevel(logging.INFO)
def serve_forever(saddr):
# temperorary fix
logger = logging
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(saddr)
s.listen(5)
logger.info("socket bound to %s:%d" % (saddr[0], saddr[1]))
try:
while 1:
cs, addr = s.accept()
logger.info("New connection established (%s:%d)", addr[0], addr[1])
d = cs.recv(2048)
d = d.lower().strip()
if d == "ping":
cs.send("pong \n")
elif d == "pong":
cs.send("ping \n")
else:
cs.send("unknown command\n")
cs.close()
logger.info("Client(%s:%d) was served and disconnected", addr[0], addr[1])
except IOError as (errno, strerror):
logger.error("I/O error - %d: %s", errno, strerror)
except KeyboardInterrupt:
logger.info("keyboard interrupt. Closing the client")
except Exception:
logger.exception("Unkown error")
try:
s.close()
logger.info("server closed successfully")
except IOError as (errno, strerror):
logger.error("error while closing the server - (%s:%d)", errno, strerror)
TOOL_DESC = """Start echo server. If no arguments are provided it starts a server with 127.0.0.1:1234 socket address."""
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=TOOL_DESC)
parser.add_argument("--host", required = False,help="host name of the server", type=int)
parser.add_argument("--port", required = False, help="port of the server", type=int)
parser.add_argument("-v", action="store_true", help="be verbose. Default value is true.")
args = parser.parse_args()
if args.v:
logger.setLevel(logging.INFO)
else:
logger.setLevel(logging.WARNING)
# default configuration
host, port = ("", 1234)
if args.host:
host = args.host
if args.port:
port = args.port
serve_forever((host, port))