请尝试使用python3和Asyncore和Asynchat模块设置一个简单的TCP服务器,代码如下 .
class Server(asyncore.dispatcher):
def __init__ (self, port, password, handler):
self.handler = handler
self.password = password
# Call parent class constructor explicitly
asyncore.dispatcher.__init__(self)
# Create socket of requested type
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
# Set it to re-use address
#self.set_reuse_addr()
# Bind to all interfaces of this host at specified port
self.bind(('', port))
# Start listening for incoming requests
self.listen(5)
def handle_accept (self):
"""Called by asyncore engine when new connection arrives"""
# Accept new connection
(sock, addr) = self.accept()
self.session = ServerSession(
sock,
addr,
self.password,
self
)
class ServerSession(asynchat.async_chat):
#def __init__ (self, sock, addr, password, plugin, server_ref):
def __init__ (self, sock, addr, password, server_ref):
# Call constructor of the parent class
asynchat.async_chat.__init__(self, sock)
# Set up input line terminator
self.set_terminator('\x03')
# Initialize input data buffer
self.data = []
#self.plugin = plugin
self.password = password
self.ip = addr[0]
self.server_ref = server_ref
def handle_connect(self):
# connection succeeded
#self.plugin.TriggerEvent("Connected")
print("Connected")
def handle_expt(self):
# connection failed
#self.plugin.TriggerEvent("NoConnection")
print("NoConnection")
self.close()
def handle_close(self):
# connection closed
#self.plugin.TriggerEvent("ConnectionLost")
#self.plugin.EndLastEvent()
print("ConnectionLost")
asynchat.async_chat.handle_close(self)
def collect_incoming_data(self, data):
# received a chunk of incoming data
data = data
self.data.append(data)
def found_terminator(self):
self.ParseIncoming(self.data)
self.data = ''
服务器设置,但是当我通过远程TCP客户端向它发送一些数据时,我收到以下错误消息:
错误:未捕获的python异常,关闭通道(:需要一个类似字节的对象,而不是'str'[C:\ Users \ EOdianosen \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ asyncore.py | read | 83] [C:\ Users \ EOdianosen \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ asyncore.py | handle_read_event | 423] [C:\用户\ EOdianosen \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ asynchat.py | handle_read | 161])ConnectionLost
它似乎可以't process what I am sending, as it thinks it'是一个字符串 . 我本来可以使用Twisted,但是我的应用程序有一个终止符 \x03 ,我没有设置终止符 .
请非常感谢任何帮助 .
亲切的问候