【发布时间】:2011-10-22 22:45:15
【问题描述】:
我正在尝试遵循 online tutorial 中关于使用标准 Python 库(版本 2.7)进行基本客户端-服务器套接字编程的示例,但我无法让该示例在 Windows(Vista)下工作。它在 Ubuntu 11.10 中运行良好,所以我知道下面的代码至少可以在基于 UNIX 的环境中运行:
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 对套接字的处理,我忽略了什么?
【问题讨论】:
-
你怎么知道程序在“接受”时停止响应?你看到“有人想要诗歌”的信息了吗?
-
因为我在从未到达的语句之后设置了一个断点。所以不,我没有看到“有人想要诗歌”的消息。
-
如果您卡在“接受”上,则说明没有人连接到您的套接字。尝试 telnet 连接到端口。下面的答案也有很好的信息。
-
是的,看起来客户端没有连接到套接字端点。我认为这与 Windows 不允许重用 localhost 接口有关(这是我正在关注的教程的作者有意介绍的一个功能) - 但我还没有找到解决方法.
标签: python sockets networking client-server winsock