我正在嘗試使用一個online tutorial關於使用標準Python庫(版本2.7)的基本客戶端 - 服務器套接字編程的示例,但我無法得到該示例在Windows(Vista)下工作。它的工作原理在Ubuntu 11.10很好,所以我知道下面的代碼至少在基於UNIX的環境中工作:
在Windows中使用Python,如何通過套接字連接發送和檢索任意數量的數據?
import optparse, os, socket, time
def parse_args():
parser = optparse.OptionParser(usage)
help = "The port to listen on. Default to a random available port."
parser.add_option('--port', type='int', help=help)
help = "The interface to listen on. Default is localhost."
parser.add_option('--iface', help=help, default='localhost')
help = "The number of seconds between sending bytes."
parser.add_option('--delay', type='float', help=help, default=.1)
help = "The number of bytes to send at a time."
parser.add_option('--num-bytes', type='int', help=help, default=10)
options, args = parser.parse_args()
if len(args) != 1:
parser.error('Provide exactly one poetry file.')
poetry_file = args[0]
if not os.path.exists(args[0]):
parser.error('No such file: %s' % poetry_file)
return options, poetry_file
def send_poetry(sock, poetry_file, num_bytes, delay):
inputf = open(poetry_file)
while True:
bytes = inputf.read(num_bytes)
if not bytes:
sock.close()
inputf.close()
return
print 'Sending %d bytes' % len(bytes)
try:
sock.sendall(bytes) # this is a blocking call
except socket.error:
sock.close()
inputf.close()
return
time.sleep(delay)
def serve(listen_socket, poetry_file, num_bytes, delay):
while True:
sock, addr = listen_socket.accept()
print 'Somebody at %s wants poetry!' % (addr,)
send_poetry(sock, poetry_file, num_bytes, delay)
def main():
options, poetry_file = parse_args()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((options.iface, options.port or 0))
sock.listen(5)
print 'Serving %s on port %s.' % (poetry_file, sock.getsockname()[1])
serve(sock, poetry_file, options.num_bytes, options.delay)
if __name__ == '__main__':
main()
程序停止只要插座在serve()
調用accept()
響應功能,並且沒有收到請求的數據,據我所知。我對Windows對套接字的處理有什麼看法?
你怎麼知道的程序停止在「接受響應「?你看到「有人想要詩歌」的訊息嗎? –
因爲我在永遠不會到達的聲明後面設置了一個斷點,所以不,我沒有看到「有人想要詩歌」的訊息 – clarkb86
如果你遇到'接受'沒有人連接到您的套接字,請嘗試telnet連接到端口,下面的答案也有很好的信息 –