Page MenuHomec4science

multiplexer
No OneTemporary

File Metadata

Created
Wed, Jan 22, 16:00

multiplexer

#!/usr/bin/env python
import socket, select, sys
# Function to broadcast chat messages to all connected clients
def broadcast_data(message, sender_socket):
for socket in CONNECTION_LIST:
if socket != sender_socket :
try :
socket.send(message)
except :
print('Inactive socket detected... closing it.')
try:
CONNECTION_LIST.remove(socket)
except:
"sock not longer in list."
socket.close()
print("Now: %d active connection(s)" % len(CONNECTION_LIST))
# MAIN
if len(sys.argv) < 2:
print("Usage : " + sys.argv[0] + " port [IP]")
sys.exit()
PORT = int(sys.argv[1])
if len(sys.argv) == 3:
HOST = sys.argv[2]
else:
HOST = "0.0.0.0"
RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
CONNECTION_LIST = []
print("Multiplexer ready (" + HOST + ":" + str(PORT) + ")")
print("Press Ctrl-C to quit.")
while 1:
try:
read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST + [server_socket],[],[])
except OSError as err:
print('SOCKET ERROR: %s' % err)
sys.exit()
except:
print
print('Multiplexer shuting down. Closing socket(s).')
for sock in CONNECTION_LIST:
sock.close()
CONNECTION_LIST.remove(sock)
print('Multiplexer is down.')
sys.exit()
for sock in read_sockets:
if sock == server_socket:
# New connection on the multiplexer socket
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print("New instrument connected to multiplexer from: %s:%s" % addr)
print("Now: %d active connection(s)" % len(CONNECTION_LIST))
else:
# Data received from an NMEA instrument socket
try:
data = sock.recv(RECV_BUFFER)
if data:
broadcast_data(data, sock)
else :
print('No data... closing socket.')
sock.close()
try:
CONNECTION_LIST.remove(sock)
except:
"sock not longer in list."
print("Now: %d active connection(s)" % len(CONNECTION_LIST))
except:
# Connection reset ? Remove sock from list then.
print('Error on recv detected... closing socket.')
sock.close()
try:
CONNECTION_LIST.remove(sock)
except:
"sock not longer in list."
print("Now: %d active connection(s)" % len(CONNECTION_LIST))
continue
server_socket.close()

Event Timeline