socket.error: [Errno 32] Broken pipe错误的原因
2014年1月26日 15:47
linux下的socket程序,尝试发送消息到已关闭的socket上,会出现此错误.
示例代码
服务端server.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #encoding=utf-8import socketimport timedef main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('0.0.0.0', 8050)) sock.listen(5) client_sock, address = sock.accept() while True: msg = client_sock.recv(1024) print msg client_sock.send('from server: %s' % msg) time.sleep(1) client_sock.close() sock.close()if __name__ == '__main__': main() |
客户端client.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #encoding=utf-8import socketimport timedef main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('0.0.0.0', 8050)) while True: sock.send('hi') print sock.recv(1024) time.sleep(1) sock.close()if __name__ == '__main__': main() |
运行server.py和client.py,然后中断client.py会出现上面错误。