简体   繁体   English

Python-Asyncore(客户端)套接字-无法确定连接状态

[英]Python - Asyncore (client) socket - Can not determaine connection status

For some reason, self.connected of the asyncore.dispatcher class doesn't consider my socket to be connected on the client side. 由于某种原因, asyncore.dispatcher类的self.connected不会将我的套接字连接到客户端。 The server side sees the socket as connected and treats it as such, but the client doesn't know if it's connected or not and handle_connect doesn't "proc", so i can't use a overridden version of it to check if the socket is connected either. 服务器端将套接字视为已连接并对其进行处理,但是客户端不知道套接字是否已连接,并且handle_connect不“ proc”,因此我无法使用其重写版本来检查是否插座已连接。

Any thoughts on this code why it ain't working: 关于此代码的任何想法为何不起作用:

#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import asyncore
from threading import *
from socket import *
from time import sleep
from os import _exit
from logger import *
from config import *

class logDispatcher(asyncore.dispatcher):
    def __init__(self, config=None):
        self.inbuffer = ''
        self.buffer = ''
        self.lockedbuffer = False
        self.is_writable = False

        asyncore.dispatcher.__init__(self)
        #Thread.__init__(self)

        self.create_socket(AF_INET, SOCK_STREAM)

        #self.is_writable = True
        #self.start()

    def compare(self, obj, otherobj):
        return (str(obj).lower() == str(otherobj).lower()[:len(str(obj))])
    def _in(self, obj, otherobj):
        return (str(obj).lower() in str(otherobj).lower())

    def parse(self):
        if self.inbuffer[-2:] != '\r\n':
            return False

        self.lockedbuffer = True
        self.inbuffer = ''
        self.lockedbuffer = False

    def readable(self):
        return True

    def handle_connect(self):
        log('Connected to ' + str(server), 'SOCK_CORE')

    def handle_close(self):
        self.close()

    def handle_read(self):
        data = self.recv(8192)
        while self.lockedbuffer:
            sleep(0.01)
        self.inbuffer += data

    def writable(self):
        return (len(self.buffer) > 0)

    def handle_write(self):
        while self.is_writable:
            sent = self.send(self.buffer)
            sleep(1)
            self.buffer = self.buffer[sent:]
            if len(self.buffer) <= 0:
                self.is_writable = False
            sleep(0.01)

    def _send(self, what):
        self.buffer += what + '\r\n'
        self.is_writable = True

    def handle_error(self):
        log('Error, closing socket!', 'SOCK_CORE')
        self.close()

    def run(self):
        log('Log socket engine initating', 'SOCK_CORE')
        self.connect((server, server_port))

        print self.connected
        sleep(3)
        print self.connected

class start(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.start()
    def run(self):
        asyncore.loop(0.1)

start()
logDisp = logDispatcher()
logDisp.run()
def handle_connect_event(self):
    self.is_connected = True

Adding that to your dispatcher will give you a way to check if the socket is connected or not, thanks to some stack trace ( python -m trace -t script.py ) in Python I managed to figure out that the asyncore class automaticly created that function for whatever reason, and it was called continiously as long as the socket was connected or in a connected state. 将其添加到您的调度程序中将为您提供一种检查套接字是否已连接的方法,这要归功于python -m trace -t script.py一些堆栈跟踪( python -m trace -t script.py ),我设法弄清楚了asyncore类是自动创建的无论出于何种原因,它都可以正常工作,只要套接字已连接或处于连接状态,它就会被连续调用。

After that, i also replaced the threaded asyncore.loop() and replaced it with a "static" placement locking your main thread, one of these two combinations (or both) solved the issue for now.. the logic isn't the same as in my problem which i don't like but i assume that i'll be needing to create my own dispach_event just like if i were to do a OpenGL GUI class where i would call dispatch_event() manually every loop some how in the thread to "keep things alive".. it's just a thought.. 在那之后,我还替换了线程化的asyncore.loop(),并用锁定您的主线程的“静态”位置替换了它,这两个组合(或两者)之一暂时解决了这个问题。.逻辑不一样就像我不喜欢的问题一样,但是我认为我将需要创建自己的dispach_event,就像我要做一个OpenGL GUI类那样,我将在每个循环中手动调用dispatch_event()并在线程中进行一些操作“让事情活着” ..这只是一个想法。

Anyway, here's a working example: 无论如何,这是一个工作示例:

#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import asyncore, socket
from threading import *
from time import sleep
from os import _exit
from logger import *
from config import *

def _map():
    return {}
def _array():
    return []

class logDispatcher(Thread, asyncore.dispatcher):
    def __init__(self, config=None):
        self.inbuffer = ''
        self.buffer = ''
        self.lockedbuffer = False
        self.is_writable = False

        self.is_connected = False

        self.exit = False
        self.initated = False

        asyncore.dispatcher.__init__(self)
        Thread.__init__(self)

        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.connect((server, server_port))
        except:
            log('Could not connect to ' + server, 'LOG_SOCK')
            return None

        self.start()

    def handle_connect_event(self):
        self.is_connected = True

    def handle_connect(self):
        self.is_connected = True
        log('Connected to ' + str(server), 'LOG_SOCK')

    def handle_close(self):
        self.is_connected = False
        self.close()

    def handle_read(self):
        data = self.recv(8192)
        while self.lockedbuffer:
            sleep(0.01)

        self.inbuffer += data


    def handle_write(self):
        while self.is_writable:
            sent = self.send(self.buffer)
            sleep(1)

            self.buffer = self.buffer[sent:]
            if len(self.buffer) <= 0:
                self.is_writable = False
            sleep(0.01)

    def _send(self, what):
        self.buffer += what + '\r\n'
        self.is_writable = True

    def run(self):
        sleep(1)
        log('Log engine initating (hooking on to main)', 'LOG_CORE')

        main = None
        for t in enumerate():
            if t.getName() == 'MainThread':
                main = t

        log('Log engine attached to main', 'LOG_CORE')

        while (main and main.isAlive()) and (self.connected or self.is_connected):
            print 'WHAM', self.connected, self.is_connected
            sleep(1)

while 1:
    logDisp = logDispatcher()
    asyncore.loop(0.1)
    log('Logserver disconnected, trying to reconnect!', 'CORE')
    sleep(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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