简体   繁体   中英

Python sockets, how to escape from infinite loop and handle exceptions

I have a script that connects to a remote server. The code is below

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((remote_host,remote_port))
s.setblocking(False)


while True:
    try:
        data = s.recv(1024)

        if not data:
           break

        pkt_type = ord(data[2]) # get pkt type

        if pkt_type == Reset:
           s.send(data)

        if pkt_type == Authenticate:
           processAuthenticate(s,data)
           break

    except:
        pass

while(True)
 .
 .
 .

I wait for reset and echo back to the server, then wait for an Authenticate packet, twiddle a few bit and echo that back to the server. Once this is done successfully I can now request data from the the server. This is done in the next while(true) loop.

Is this the best way of doing this. Sometimes when I run the script I get an error, what is the simplest way of handling the exception and preventing execuation of the next wile loop?

Thanks

A Finite State Machine (FSM) is pretty much the canonical way to do this sort of thing. A good reference for doing FSMs in Python is this: http://wiki.python.org/moin/FiniteStateMachine

EDIT: Looks like a FSM should be handy here.

Actually, I suggest you take a look at Twisted Reactor - haven't used it myself (yet), but it does all the bulk work and nasty stuff that you would have to implement yourself if using a FSM and an event loop (which your while -loop essentially is)

EDIT 2:

A few notes (while waiting for your complete code)

  1. the fact that you have 2 consecutive while(true) is, well, odd
  2. you probably want to move the except: statement up, before the if not data statement and replace pass with continue
  3. ord(data[2]) suggests that you are using a binary protocol, you really should consider using the struct modules unpack() and pack() instead.

In addition to the above tips, you need to buffer the data - when using a stream protocol you can't just assume that you will get all the data you want in one call to recv. Instead you must take what you read from recv and add it to a buffer, then examine the buffer to see if it contains all the data for a message yet. If it does, extract the message, handle it, then repeat with the rest of the buffer. When you can't extract any further messages, you go back and read more from the socket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM