Python socket奇怪的行为

时间:2015-02-27 14:57:47

标签: python sockets netcat

我无法理解为什么这段代码能正常运行,

echo as3333 | nc stat.ripe.net 43

但Python中的等效代码不返回任何内容

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('stat.ripe.net', 43))
sock.send('as3333'.encode('utf-8'))
tmp = sock.recv(1024)
print(tmp.decode('utf-8')) #no bytes there
sock.close()

谢谢!

1 个答案:

答案 0 :(得分:1)

它不完全一样。您忘记了换行符sendall。固定代码:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('stat.ripe.net', 43))
sock.sendall('as3333\r\n'.encode('utf-8'))

response = b''
while True:
    tmp = sock.recv(65536)
    if not tmp:
        break
    response += tmp

print(response.decode('utf-8'))
sock.close()