无法在python套接字中找到以太网或套接字连接

时间:2014-01-16 14:44:52

标签: python sockets python-2.7

我有一个小型客户端应用程序,需要维护与服务器的持久套接字连接。

连接建立似乎工作正常。当服务器关闭我能够检测到的套接字时。

但是当客户端以太网电缆被拔掉时。当我尝试在袜子中发送或接收数据时,它永远不会抛出异常。

当我尝试发送时,我获得发送数据成功,当我尝试接收时,我得到接收超时

我班上缺少什么。请指导

注意:套接字几乎需要14分钟才能找到断开连接

保持活动数据:

echo 30 > /proc/sys/net/ipv4/tcp_keepalive_intvl
echo 3 > /proc/sys/net/ipv4/tcp_keepalive_probes
echo 30 > /proc/sys/net/ipv4/tcp_keepalive_time

代码实现:

import logFormat as log
import socket
import traceback
import sys
import select
import time
import messageId as messasgeId  # Name convention to be decided Many DB access done through this class

def synchronized(L):
    def lock_around(f):
        def locked(*a, **k):
            with L:
                return f(*a, **k)
        locked.__name__ = f.__name__
        locked.__doc__ = f.__doc__
        return locked
    return lock_around


class socketHandler(object):
    __single = None  # the one, true Singleton

    def __new__(classtype, *args, **kwargs):
        if classtype != type(classtype.__single):
            classtype.__single = object.__new__(classtype, *args, **kwargs)
        return classtype.__single

    def __init__(self, name=None):
        self.name = name
        self.throttleCount = 100    
        self.loggerCount = 0
        self.timeoutDefault=0.2    

    def socketSend(self, data):
        try:
            self.sock.send(data)
            log.debugLog("Socket data send complete", True)
            return True
        except:
            log.debugLog("Socket data send with error/timeout", True)
            raise

    def recieveProtoBufHeader(self, headerLength, timeout=10):
        try:
            self.sock.settimeout(timeout)
            expHeaderBytes = ord(headerLength)
            log.debugLog("Expected socket data length: %s with timeout: %s" % (expHeaderBytes, timeout), True)
            HeaderData = self.sock.recv(expHeaderBytes)


            log.debugLog("Data received in socket: %s" % HeaderData, True)
            self.sock.settimeout(self.timeoutDefault)
            return HeaderData
        except:
            log.debugLog("recieveProtoBufHeader with error/timeout", True)
            raise

    def recieveProtoBufData(self, dataSize, timeout=0.1):
        try:
            log.debugLog("Expected socket data length: %s with timeout: %s" % (dataSize, timeout), True)
            self.sock.settimeout(timeout)
            dataBuffer = self.sock.recv(dataSize)
            log.debugLog("Data received in socket: %s" % dataBuffer, True)
            self.sock.settimeout(self.timeoutDefault)
            return dataBuffer
        except:
            log.debugLog("recieveProtoBufData with error/timeout", True)
            raise

    def recieveData(self, dataSize, timeout=0.1):
        try:
            self.sock.settimeout(timeout)
            dataBuffer = self.sock.recv(1)
            if len(dataBuffer) == dataSize:
                log.debugLog("Data received in socket: %s" % dataBuffer.encode('hex'), True)
                log.debugLog("Data received length: %s" % len(dataBuffer), True)
            else:
                self.sock.close()
                log.debugLog("Server side socket closed raising socket error", True)
                raise socket.error, "Socket error raised"
            self.sock.settimeout(self.timeoutDefault)
            return dataBuffer
        except socket.timeout:
            raise  # Can add log foo socket timeout
        except:
            log.debugLog("Unknown exception occurred so closing socket ", True)
            self.sock.close()
            raise

    def recieveDataCheck(self):
        try:
            self.sock.settimeout(0.2)
            dataBuffer = self.sock.recv(1)
            if len(dataBuffer) == 1:
                log.debugLog("Data received in socket: %s" % dataBuffer.encode('hex'), True)
                log.debugLog("Data received length: %s" % len(dataBuffer), True)
            else:
                self.sock.close()
                log.debugLog("Server side socket closed raising socket error", True)
                raise socket.error, "Socket error raised"
            return dataBuffer
        except socket.timeout:
            raise  # Can add log foo socket timeout
        except:
            log.debugLog("Unknown exception occurred so closing socket ", True)
            self.sock.close()
            raise

    def closeSocket(self):
        try:
            self.sock.close()
            self.sock = None
            return True
        except:
            log.debugLog("Close socket with error", True)
            raise

    def recieveCheck(self):
        try:
            ready = select.select([self.sock], [], [], 0.2)
            print ready
            if len(ready[0]) == 0:
                return True
            else:
                return False
        except:
            raise

    def connectSocket(self, retryCount=5):
        try:
            self.loggerCount+=1
            if self.loggerCount % self.throttleCount == 0:
                throttleLog=True
            else:
                throttleLog=False
            #host = "192.168.10.134"
            host = messasgeId.getSwitchIP()
            # host = "localhost"
            #port = int(8001)
            port = int(messasgeId.getSwitchPort())         
            log.debugLog("connection with switch server ip: %s port: %s on progress" % (host, port), True)
            while retryCount:
                self.sock = None
                self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                #self.sock.bind(host,port)
                self.sock.settimeout(0.1)
                try:
                    self.sock.connect((host, port))
                    #assert(self.recieveCheck())
                    log.debugLog("Socket connection established successfully", True)
                    self.loggerCount = 0
                    return True
                except:
                    log.debugLog("Socket Connection Retry Count Remaining Progress(%s)" % retryCount, True)
                    time.sleep(5)
                    retryCount -= 1
                    if retryCount == 0:
                        return False
            return False
        except:
            log.debugLog("Unexpected error in socket connection", True)
            raise

0 个答案:

没有答案