Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issues with socket programming - python

I am doing a client-server project for my college project, we have to allocate the login to the client.

Client system will request its status for every 2 seconds(to check whether the client is locked or unlocked). and server will accept the client request and reply the client status to the system.

But the problem is server thread is not responding to the client request.

CLIENT THREAD:

def checkPort():
  while True:
    try:
        s = socket.socket()     
        s.connect((host, port))     
        s.send('pc1')                 # send PC name to the server
        status = s.recv(1024)         # receive the status from the server

        if status == "unlock":
            disableIntrrupts()        # enable all the functions of system
        else:
            enableInterrupts()        # enable all the functions of system

        time.sleep(5)                
        s.close()

    except Exception:
        pass

SERVER THREAD:

def check_port():
    while True:
      try:
        print "hello loop is repeating"
        conn, addr = s.accept()
        data = conn.recv(1024)

        if exit_on_click == 1:
            break
        if (any(sublist[0] == data for sublist in available_sys)):
            print "locked"
            conn.send("lock")
        elif (any(sublist[0] == data for sublist in occupied_sys)):
            conn.send("unlock")
            print "unlocked"
        else:
            print "added to gui for first time"
            available_sys.append([data,addr[0],nameText,usnText,branchText])
            availSysList.insert('end',data)
      except Exception:
            pass

But my problem is server thread is not executing more than 2 time, So its unable to accept client request more than one time. can't we handle multiple client sockets using single server socket? How to handle multiple client request from server ?

Thanks for any help !!

like image 842
Raj Avatar asked Feb 07 '26 21:02

Raj


1 Answers

Its because your server, will block waiting for a new connection on this line

conn, addr = s.accept()

This is because calls like .accept and .read are blocking calls that hold the process

You need to consider an alternative design, where in you either.

  • Have one process per connection (this idea is stupid)
  • One thread per connection (this idea is less stupid than the first but still mostly foolish)
  • Have a non blocking design that allows multiple clients and read/write without blocking execution.

To achieve the first, look at multiprocessing, the second is threading the third is slightly more complicated to get your head around but will yield the best results, the go to library for event driven code in Python is twisted but there are others like

  • gevent
  • tulip
  • tornado

And so so many more that I haven't listed here.

like image 187
Jakob Bowyer Avatar answered Feb 09 '26 10:02

Jakob Bowyer