Commit 126b9118 authored by Alan Marchiori's avatar Alan Marchiori

tcp server added

parent 3dd59ede
"""
Basic tcp echo/caps server
Alan Marchiori 2019
"""
import logging
import socket
import time
import argparse
def handle_req(skt, data, addr, log, server_port):
"handle a single request"
# interpret as utf-8 string, uppercase, then convert (encode)
# as raw bytes for the network
log.info("{} -> {}: {}".format(addr, server_port, data))
newdata = data.decode("utf-8").upper().encode()
time.sleep(3) # processing delay
#skt.sendto(newdata, addr)
skt.send(newdata) # note change to send since the socket is connected
log.info("{} <- {}: {}".format(addr, server_port, newdata))
def main(addr, port):
log = logging.getLogger()
server_port = (addr, port)
log.info("Starting server on {}".format(server_port))
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as skt:
skt.bind(server_port) # bind socket to the TCP port
# now the server is bound, we have to first accept
# conections and then we can communicate
skt.listen() # listen for connections
# this assumes we close the client socket before
# the next client connects
while True:
# This blocks until a connection is made
# it returns a new (connected) socket object and the
# remote address
clientsocket, clientaddress = skt.accept()
while True:
#data, addr = skt.recvfrom(1024) # blocking
data = clientsocket.recv(1024) # blocking, note not recvfrom!
if data:
handle_req(clientsocket,
data,
clientaddress,
log,
server_port)
else:
log.info("*EOF*, goodbye!")
break
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=__doc__)
parser.add_argument(
'-a', '--addr', type=str,
help='ip address of the server', required=False,
default="127.0.0.1")
parser.add_argument(
'-p', '--port', type=int,
help='port the server listens on', required=False,
default=8888)
FORMAT = '%(asctime)-15s %(levelname)-6s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
args = parser.parse_args()
# args must match main's parameters!
main(**vars(args))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment