I'm learning python and trying to create a socket handler. The service will bind to a socket and listen on it. Once a connection is received it will accept and hand-over the socket object to another new python process to handle the connection. If you have simultaneous connections there will be 1 processes to handle each connection. The problem is the variable name for the Process object; it needs to increment it otherwise it will create objects with the same name. The full code below: -
import socket
import multiprocessing
def conn_handler(obj_client_conn_socket):
byt_recv_msg = obj_client_conn_socket.recv(1024)
str_recv_msg = byt_recv_msg.decode()
print('here')
print('str_recv_msg(%s)' % str_recv_msg)
obj_client_conn_socket.close()
def main():
tup_svr_addr_port = ('127.0.0.1', 8080)
obj_listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
obj_listening_socket.bind(tup_svr_addr_port)
except:
print('Unable to bind port')
try:
obj_listening_socket.listen()
except:
print('Unable to listen on port')
while 1:
try:
obj_client_conn_socket, client_addr = obj_listening_socket.accept()
except:
print('unable to accept conn.')
proc_conn_handler = multiprocessing.Process(target=conn_handler, args=(obj_client_conn_socket,))
proc_conn_handler.start()
obj_listening_socket.close()
The bit that I need help on: -
while 1:
try:
obj_client_conn_socket, client_addr = obj_listening_socket.accept()
except:
print('unable to accept conn.')
proc_conn_handler = multiprocessing.Process(target=conn_handler, args=(obj_client_conn_socket,))
proc_conn_handler.start()
Thanks Hayden