简体   繁体   English

从套接字读取的Python初始返回一些意外字符

[英]Python initial read from socket returns some unexpected characters

I have a Python socket server that I'm trying to read text commands from a line at a time, code is below. 我有一个Python套接字服务器,我想一次从一行中读取文本命令,下面是代码。 The first time it is run, line contains what look like some garbage characters before the data. 第一次运行时,line包含数据前的一些垃圾字符。 On subsequent calls to readline I get the exact data I typed in from the telnet client (Putty). 在随后的readline调用中,我获得了从telnet客户端(Putty)中键入的确切数据。 Why am I getting these first few apparent garbage characters. 为什么我会得到这些头几个明显的垃圾字符。 Eg if I type in _return_ , line contains \\u18\\u01\\u03d\\r\\n ' 例如,如果我输入_return_ ,则该行包含\\u18\\u01\\u03d\\r\\n '

    HOST = ''
    PORT = 27001
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    while True:
        conn, address = s.accept()
        print 'Got new CLI connection'
        f = conn.makefile()
        f.flush()
        while True:
            try:
                self.PrintBanner(conn)
                self.PrintMenu(conn)
                line = f.readline()
                if line.lower()[:1] == 'd':
                    self.MenuFieldRequestStatus(conn)
                    f.readline()
            except:
                s.close()

You need to make sure and use "RAW" mode in this case. 在这种情况下,您需要确定并使用“ RAW”模式。 Otherwise, your telnet client is trying to discover and negotiate with a telnet server. 否则,您的telnet客户端将尝试发现并与telnet服务器协商。 See this link for more info: 有关更多信息,请参见此链接:

3.6 Making raw TCP connections 3.6建立原始TCP连接

You could probably switch "Telnet negotiation mode" to passive in the Telnet settings area too. 您可能也可以在Telnet设置区域中将“ Telnet协商模式”切换为被动。

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

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