Created
March 15, 2020 14:08
-
-
Save pedrominicz/c26d8f8efc7148f387c467197f8c98a2 to your computer and use it in GitHub Desktop.
Server mediated inter-process communication.
This file contains 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 itertools | |
import os | |
import socket | |
import threading | |
import time | |
# This program illustrates a simple TCP server used to mediate inter-process | |
# communication. Three processes are created: a server, a producer, and a | |
# consumer. The server creates a thread to handle each incoming connection. | |
address = (socket.gethostname(), 5000) | |
if os.fork() != 0: | |
# Create a TCP socket for the _actual_ server. | |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server.bind(address) | |
server.listen(2) | |
connections = [] | |
# Each connection will execute this function on a separate thread. | |
def thread(connection): | |
while True: | |
# `socket.socket.recv` blocks. This is not a proble, however, | |
# because the loop below is able to send messages even if the | |
# thread that owns another connection is currently blocked waiting | |
# a message. | |
message = connection.recv(4096) | |
for connection in connections: | |
connection.send(message) | |
while True: | |
connection, address = server.accept() | |
connections.append(connection) | |
# Note the argument `args` requires a tuple and that `(connection, )` | |
# is parsed as a tuple while `(connection)` is equivalent to | |
# `connection` but with superfluous parenthesis. | |
threading.Thread(target=thread, args=(connection, )).start() | |
else: | |
if os.fork() == 0: | |
# Create a TCP socket for the producer. | |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server.connect(address) | |
# `itertools.count` returns an iterator that counts from zero to | |
# infinity. | |
for i in itertools.count(): | |
server.send(str(i).encode()) | |
time.sleep(1) | |
else: | |
# Create a TCP socket for the consumer. | |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server.connect(address) | |
while True: | |
print(server.recv(4096).decode()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment