简体   繁体   English

Python socket奇怪的行为

[英]Python socket strange behavior

I can't understand why this code works fine, 我不明白为什么这段代码工作正常,

echo as3333 | nc stat.ripe.net 43

but the equivalent code in Python returns nothing 但是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()

Thanks! 谢谢!

It is not exactly the same. 它不完全一样。 You forgot the newline and sendall . 你忘记了换行符和sendall Fixed code: 固定代码:

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()

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

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