Commit 63e95db6 authored by Alan Marchiori's avatar Alan Marchiori

reorganized

parent 126b9118
"""
Cap server with asyncio
Alan Marchiori
"""
import logging
import asyncio
import argparse
class MyUdpProtocol:
def __init__(self, log, loop):
self.log = log
self.loop = loop
def connection_made(self, transport):
self.transport = transport
self.log.info("Connection made with {}".format(self.transport))
async def handle_resp(self, data,addr):
self.log.info("{} --> {}".format(addr, data))
newdata = data.decode("utf-8").upper().encode()
await asyncio.sleep(3) # simulate delay
self.transport.sendto(newdata, addr)
log.info("{} <-- {}".format(
addr, newdata))
def datagram_received(self, data, addr):
self.loop.create_task(self.handle_resp(data,addr))
if __name__=="__main__":
FORMAT = '%(asctime)-15s %(levelname)-6s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
log = logging.getLogger()
parser = argparse.ArgumentParser(
description = __doc__
)
parser.add_argument(
'-a', '--addr', type=str,
help = 'the ip address the server will listen on (default: 127.0.0.1)',
default = '127.0.0.1')
parser.add_argument(
'-p', '--port', type=int,
help = 'the port number to listen on (default: 8888)',
default = 8888
)
args = parser.parse_args()
log.debug("Got args: {}".format(args))
# get the event loop for the current thread
loop = asyncio.get_event_loop()
server_task = loop.create_datagram_endpoint(
lambda: MyUdpProtocol(log, loop),
local_addr = (args.addr, args.port)
)
loop.create_task(server_task)
try:
loop.run_forever()
except KeyboardInterrupt:
log.info("Ctrl-c: quit")
finally:
loop.close()
log.info("Shutdown")
"""
Basic TCP echo/caps server
Alan Marchiori 2019
"""
import logging
import socket
import time
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.send(newdata)
log.info("{} <- {}: {}".format(addr, server_port, newdata))
def main(server_port=('127.0.0.1', 8888)):
log = logging.getLogger()
log.info("Starting server on {}".format(server_port))
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as skt:
skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
skt.bind(server_port) # bind socket to the UDP port
skt.listen()
while True:
# wait for a connection
client_skt, client_addr = skt.accept()
log.info("connection from: {}".format(client_addr))
data = client_skt.recv(1024) # blocking
if data:
handle_req(client_skt, data, client_addr, log, server_port)
client_skt.shutdown(socket.SHUT_RDWR)
client_skt.close()
else:
log.info("*EOF*, goodbye!")
break
if __name__ == "__main__":
FORMAT = '%(asctime)-15s %(levelname)-6s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
main()
"""
Basic udp echo/caps server (threading)
Alan Marchiori 2019
"""
import logging
import socket
import time
import threading
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)
log.info("{} <- {}: {}".format(addr, server_port, newdata))
def main(server_port=('127.0.0.1', 8888)):
log = logging.getLogger()
log.info("Starting server on {}".format(server_port))
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as skt:
skt.bind(server_port) # bind socket to the UDP port
while True:
data, addr = skt.recvfrom(1024) # blockingsocketserver
if data:
t = threading.Thread(
target=handle_req,
args=(skt, data, addr, log, server_port))
t.start()
else:
log.info("*EOF*, goodbye!")
break
if __name__ == "__main__":
FORMAT = '%(asctime)-15s %(levelname)-6s [%(threadName)s]: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
main()
......@@ -27,6 +27,11 @@ def main(addr, port):
log.info("Starting server on {}".format(server_port))
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as skt:
# socket options defined here https://linux.die.net/man/3/setsockopt
if skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1):
log.error("setsockopt failed.")
exit(-1)
skt.bind(server_port) # bind socket to the TCP port
# now the server is bound, we have to first accept
......@@ -41,7 +46,13 @@ def main(addr, port):
# remote address
clientsocket, clientaddress = skt.accept()
while True:
log.info("Connection from {}".format(
clientaddress
))
# handle one packet only!
#while True:
if True:
#data, addr = skt.recvfrom(1024) # blocking
data = clientsocket.recv(1024) # blocking, note not recvfrom!
if data:
......@@ -52,7 +63,13 @@ def main(addr, port):
server_port)
else:
log.info("*EOF*, goodbye!")
break
# close the client socket to free OS resources
log.info("shutting down socket to {}".format(clientaddress))
clientsocket.shutdown(socket.SHUT_RDWR)
clientsocket.close()
# only need break if handling mutiple packets per client
#break
if __name__ == "__main__":
......
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