Python 为什么telnet和netcat在这个扭曲的例子中失败了?

Python 为什么telnet和netcat在这个扭曲的例子中失败了?,python,twisted,telnet,netcat,Python,Twisted,Telnet,Netcat,我正在跟踪一个,并尝试了该文章中的以下代码: # Read username, output from non-empty factory, drop connections from twisted.internet import protocol, reactor from twisted.protocols import basic class FingerProtocol(basic.LineReceiver): def lineReceived(self, user):

我正在跟踪一个,并尝试了该文章中的以下代码:

# Read username, output from non-empty factory, drop connections

from twisted.internet import protocol, reactor
from twisted.protocols import basic

class FingerProtocol(basic.LineReceiver):
    def lineReceived(self, user):
        self.transport.write(self.factory.getUser(user)+"\r\n")
        self.transport.loseConnection()

class FingerFactory(protocol.ServerFactory):
    protocol = FingerProtocol

    def __init__(self, **kwargs):
        self.users = kwargs

    def getUser(self, user):
        return self.users.get(user, "No such user")

reactor.listenTCP(1079, FingerFactory(moshez='Happy and well'))
reactor.run()

我尝试了
nclocalhost 1079
,但它只是挂起:没有回复。但是,
telnet localhost 1079
工作正常。为什么?

使用wireshark,我发现如下:
telnet
发送0x0d,然后发送0x0a(即“\r\n”)作为线路终止符。但是,
netcat
仅发送0x0a。这是在Ubuntu上(也在OSX上)

显然,Twisted中的
LineReceiver
协议需要\r来引发“line received”事件

至少有6个版本的
netcat
,但OS X上的版本(接近FreeBSD)有一个
-c
选项,该选项将\r\n附加到每行的末尾。使用此选项可以修复此问题

$ nc -c localhost 1079 
moshez
Happy and well

注意:
LineReceiver
有一个名为
delimiter
的类变量,允许使用任何下线字符。设置
delimiter='\n'
可以避免netcat需要
-c
选项。

使用wireshark,我发现:
telnet
发送0x0d,然后发送0x0a(即,“\r\n”)作为线路终止符。但是,
netcat
仅发送0x0a。这是在Ubuntu上(也在OSX上)

显然,Twisted中的
LineReceiver
协议需要\r来引发“line received”事件

至少有6个版本的
netcat
,但OS X上的版本(接近FreeBSD)有一个
-c
选项,该选项将\r\n附加到每行的末尾。使用此选项可以修复此问题

$ nc -c localhost 1079 
moshez
Happy and well

注意:
LineReceiver
有一个名为
delimiter
的类变量,允许使用任何下线字符。设置
delimiter='\n'
可以避免netcat需要
-c
选项。

在linux上,您需要使用CRLF作为下线

从nc手册页:

-C、 --crlf(将crlf用作下线)。 此选项告知Ncat转换LF。CRLF的行结束。从标准输入获取输入时。。这对于使用CRLF作为终端的许多常见纯文本协议中的一种直接从终端与一些严格的服务器进行通信非常有用


在linux上,您需要使用CRLF作为EOL

从nc手册页:

-C、 --crlf(将crlf用作下线)。 此选项告知Ncat转换LF。CRLF的行结束。从标准输入获取输入时。。这对于使用CRLF作为终端的许多常见纯文本协议中的一种直接从终端与一些严格的服务器进行通信非常有用


这是100%正确的答案,因此您应该接受您自己的答案:)网站要求我等待2天才能这样做。:)这是100%正确的答案,因此您应该接受您自己的答案:)网站要求我等待2天才能这样做。:)