Python socket connection exception

强颜欢笑 提交于 2019-12-30 01:09:07

问题


I have a socket-connection going on and I wanna improve the exception handling and Im stuck. Whenever I use the socket.connect(server_address) function with an invalid argument the program stops, but doesnt seem to throw any exceptions. Heres my code

import socket
import sys
import struct
class ARToolkit():

    def __init__(self):
        self.x = 0
        self.y = 0
        self.z = 0
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.logging = False


    def connect(self,server_address):
        try:
            self.sock.connect(server_address)
        except socket.error, msg:
            print "Couldnt connect with the socket-server: %s\n terminating program" % msg
            sys.exit(1)


    def initiate(self):
        self.sock.send("start_logging")

    def log(self):
        self.logging  = True  
        buf = self.sock.recv(6000)
        if len(buf)>0:
            nbuf = buf[len(buf)-12:len(buf)]
            self.x, self.y, self.z = struct.unpack("<iii", nbuf)





    def stop_logging(self):
        print "Stopping logging"
        self.logging = False
        self.sock.close()

The class maybe looks a bit wierd but its used for receiving coordinates from another computer running ARToolKit. Anyway, the issue is at the function connect():

def connect(self,server_address):
        try:
            self.sock.connect(server_address)
        except socket.error, msg:
            print "Couldnt connect with the socket-server: %s\n terminating program" % msg
            sys.exit(1)

If I call that function with a random IP-address and portnumber the whole program just stops up at the line:

self.sock.connect(server_address)

The documentation I've read states that in case of an error it will throw a socket.error-exception. I've also tried with just:

except Exception, msg:

This, if I'm not mistaken, will catch any exceptions, and still it yields no result. I would be very grateful for a helping hand. Also, is it okay to exit programs using sys.exit when an unwanted exception occurs?

Thank you


回答1:


If you have chosen a random, but valid, IP address and port, socket.connect() will attempt to make a connection to that endpoint. By default, if no explicit timeout is set for the socket, it will block while doing so and eventually timeout, raising exception socket.error: [Errno 110] Connection timed out.

The default timeout on my machine is 120 seconds. Perhaps you are not waiting long enough for socket.connect() to return (or timeout)?

You can try reducing the timeout like this:

import socket

s = socket.socket()
s.settimeout(5)   # 5 seconds
try:
    s.connect(('123.123.123.123', 12345))         # "random" IP address and port
except socket.error, exc:
    print "Caught exception socket.error : %s" % exc

Note that if a timeout is explicitly set for the socket, the exception will be socket.timeout which is derived from socket.error and will therefore be caught by the above except clause.




回答2:


The problem with your last general exception is the colon placement. It needs to be after the entire exception, not after the except statement. Thus to capture all exceptions you would need to do:

except Exception,msg:

However from Python 2.6+ you should use the as statement instead of a comma like so:

except Exception as msg:

I was able to run the code fine (note you need to throw in a tuple to the connect method). If you want to specifically catch only socket errors then you would need to except the socket.error class. Like you have:

except socket.error as msg:

If you want to make sure that a tuple is entered simply add another exception loop:

except socket.error as msg:
    print "Socket Error: %s" % msg
except TypeError as msg:
    print "Type Error: %s" % msg


来源:https://stackoverflow.com/questions/25447803/python-socket-connection-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!