0

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

Hayden
  • 1
  • 1
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Carcigenicate Nov 22 '20 at 15:15
  • 2
    If you need to track multiple processes, put the processes in a list, and index the list. – Carcigenicate Nov 22 '20 at 15:15
  • Ok I can create a list as lis_proc_conn_handler = [] and do lis_proc_conn_handler.append(multiprocessing.Process(target=conn_handler, args=(obj_client_conn_socket,))) – Hayden Nov 22 '20 at 18:42
  • What would happen to the processing object once the process has finished and died? – Hayden Nov 22 '20 at 19:23
  • I would remain in the list, and would be garbage collected once it goes it out of scope. – Carcigenicate Nov 22 '20 at 19:41
  • Thanks, a bit late in day but your suggestion Carcigenicate worked – Hayden Feb 19 '23 at 16:52

0 Answers0