Python套接字连接异常 [英] Python socket connection exception

查看:232
本文介绍了Python套接字连接异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个socket连接,我想改进异常处理和Im卡住。每当我使用无效参数的socket.connect(server_address)函数,程序停止,但似乎没有抛出任何异常。我的代码

  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)
除了socket.error,msg:
打印无法连接到套接字服务器:%s\\\
终止程序%msg
sys.exit (1)


def start(self):
self.sock.send(start_logging)

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





def stop_logging(self):
打印停止日志记录
self.logging = False
self.sock.close()
/ pre>

该类可能看起来有点恶心,但它用于从另一台运行ARToolKit的计算机接收坐标。无论如何,问题在函数 connect()

  def connect(self,server_address):
try:
self.sock.connect(server_address)
except socket.error,msg:
print无法连接到套接字服务器: %s\\\
终止程序%msg
sys.exit(1)

如果我用一个随机的IP地址和portnumber来调用该函数,整个程序只是停在一行:

  self.sock。 connect(server_address)

我读过的文档指出,如果发生错误,它会抛出socket.error的异常。我也试过只是:

 除了异常,msg:
pre>

如果我没有错误,会捕获任何异常,仍然不会产生结果。我将非常感谢帮忙。另外,当一个不需要的异常发生时,可以使用sys.exit退出程序吗?



谢谢

解决方案

如果您选择了一个随机但有效的IP地址和端口,则 socket.connect()将尝试建立连接那个端点。默认情况下,如果没有为套接字设置显式超时,它会在执行此操作时阻止,并最终超时,引发异常 socket.error:[Errno 110] Connection超时



我机器上的默认超时时间为120秒。也许你不等待足够长的时间,以便 socket.connect()返回(或超时)?



你可以尝试减少这样的超时时间:

  import socket 

s = socket.socket()
s.settimeout(5)#5秒
try:
s.connect(('123.123.123.123',12345))#随机IP地址和端口
除了socket.error ,exc:
print捕获异常socket.error:%s%exc

注意如果为套接字显式设置了超时,则异常将为 socket.timeout ,该引用来自 socket.error 因此将被上述的除外条款所捕获。


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

解决方案

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.

这篇关于Python套接字连接异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆