我不明白为什么这段代码可以正常工作,
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()
谢谢!
最佳答案
它并不完全相同。您忘记了换行符和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()