Created
April 25, 2022 17:16
-
-
Save tiagocoutinho/b471b792abadf944d5268c7db4f5cba8 to your computer and use it in GitHub Desktop.
socket server multiprocess
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import socket | |
import logging | |
def cb(sock): | |
reader = sock.makefile('rb') | |
for line in reader: | |
sock.sendall(line[::-1]) | |
def accept(sock, log): | |
while True: | |
log.info("waiting for requests") | |
conn, addr = sock.accept() | |
log.info("client connected from %s", addr) | |
try: | |
cb(conn) | |
except Exception as error: | |
log.error("error: %r", error) | |
finally: | |
print("client disconnected from %r", addr) | |
def main(): | |
logging.basicConfig(level="INFO") | |
sock = socket.create_server(("", 20_000), backlog=0) | |
pid = os.fork() | |
name = "parent" if pid else "child" | |
log = logging.root.getChild(f"{name}({os.getpid()})") | |
try: | |
accept(sock, log) | |
except KeyboardInterrupt: | |
log.info("Ctrl-C pressed. Bailing out!") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment