socket.error: [Errno 32] Broken pipe错误的原因


linux下的socket程序,尝试发送消息到已关闭的socket上,会出现此错误.

示例代码 服务端server.py ```python

encoding=utf-8

import socket import time

def main(): sock = socket.socket(socket.AFINET, socket.SOCKSTREAM) 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

#encoding=utf-8
import socket
import time


def 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会出现上面错误。



上篇: ssh在远程执行多个命令 下篇: 理解select模块--等待IO完成