gpt4 book ai didi

python - 当我在柴油中使用产量时,telnet 连接关闭

转载 作者:行者123 更新时间:2023-12-01 05:40:40 25 4
gpt4 key购买 nike

嗨,我想使用 diesel 创建聊天服务器。我使用此代码来运行 simple chat server :

from diesel import Application, Service, until_eol, fire, wait

def chat_server(addr):
my_nick = (yield until_eol()).strip()
while True:
my_message, other_message = yield (until_eol(), wait('chat_message'))
if my_message:
yield fire('chat_message', (my_nick, my_message.strip()))
else:
nick, message = other_message
yield "<%s> %s\r\n" % (nick, message)

app = Application()
app.add_service(Service(chat_server, 8000))
app.run()

但是当我尝试远程登录该服务器时,远程登录连接被外部主机关闭。

[nima@ca005 Desktop]$ telnet localhost 8000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.

当我从代码中删除yield时,我与服务器的连接没有问题。

def chat_server(addr):
my_nick = until_eol().strip()
while True:
message = diesel.until_eol()
shouted_message = my_nick + ":" + message
diesel.send(shouted_message)
my_message = until_eol()
other_message = wait('chat_message')
if my_message:
fire('chat_message', (my_nick, my_message.strip()))

这段代码有什么问题?

最佳答案

也许是这样的。它可能不会立即起作用,因为我不熟悉柴油的工作原理。

import StringIO
import socket
import threading

from diesel import Application, Service, until_eol, fire, wait

class socket_thread(threading.Thread):

def __init__(self, line_filter = None):
threading.Thread.__init__(self)
self.daemon = True
self.lock = threading.Lock()
self.event = threading.Event()
self.event.clear()
self.buffer = StringIO.StringIO()
if(line_filter == None):
self.line_filter = lambda x: x
else:
self.line_filter = line_filter

def run(self):
message = True
while message:
message = diesel.until_eol()

self.lock.acquire()
self.buffer.write(message)
self.lock.release()
self.event.set()

def readlines(self):
self.lock.acquire()

self.buffer.seek(0)
raw_lines = self.buffer.readlines()
self.buffer.truncate(0)

self.lock.release()

lines = map(self.line_filter, raw_lines)
return lines

def chat_server(addr):
server_recv = socket_thread()
my_nick = until_eol().strip()
data = []
server_recv.start()
while True:
server_recv.event.wait()
data = server_recv.readlines()
if(data):
shouted_message = my_nick + ":" + data
diesel.send(shouted_message)
server_recv.event.clear()

my_message = until_eol()
other_message = wait('chat_message')
if my_message:
fire('chat_message', (my_nick, my_message.strip()))

app = Application()
app.add_service(Service(chat_server, 8000))
app.run()

关于python - 当我在柴油中使用产量时,telnet 连接关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17628182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com