ue_pe_web/scripts/02_sockets/src/sockets/sockets_complete.py
2024-02-01 09:33:41 +01:00

70 lines
1.6 KiB
Python

######################################################################
# Copyright (c) Boris Baldassari, Adrien Luxey-Bitri
#
# This program and the accompanying materials are made
# available under the terms of the Eclipse Public License 2.0
# which is available at https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
######################################################################
"""
This module plays with sockets.
More info.
"""
import argparse
import socket
def _parse_args():
"""
Parses arguments from command line.
"""
parser = argparse.ArgumentParser(description="Utilities to use network sockets.")
parser.add_argument('-p', '--port',
help='Port number to open')
args = parser.parse_args()
return args
def answer(addr):
"""
Returns an answer to the connection.
:return: A string.
"""
out = f"Hello {addr[0]}! You are using port {addr[1]}. Have a nice day!\n"
return out
def server(port: int=4444):
"""
Opens a socket on a given port and listens to incoming
requests. When a request comes in, accepts the connection,
sends a message back and hangs up (closes), indefinitely.
:param port: Port number to listen on.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", port))
s.listen()
while True:
c, addr = s.accept()
print('Got connection from', addr)
c.send(answer(addr).encode('utf-8'))
c.close()
if __name__ == '__main__':
# Parse command-line arguments
args = _parse_args()
# Start our server
server(int(args.port))