死锁发生在当一个服务器和客户端同时试图往一个连接上写东西和同时从一个连接上读的时候。在这种情况下没有进程可以得到任何数据。
#!/usr/bin/env python #-*- coding:utf-8 -*- #测试锁死的情况 import socket, traceback host = ‘‘ #主机设为空,程序就可以接收来自任何客户端的连接 port = 51422 #设置端口,选择一个任意大于1024的端口即可 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #创建socket对象, s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #把socket设置成可复用的 s.bind((host, port)) s.listen(5) while True: try: clientsock, clientaddr = s.accept() except KeyboardInterrupt: raise except: traceback.print_exc() continue try: print "Got connection from", clientsock.getpeername() while 1: data = clientsock.recv(4096) #把在客户端写入的数据返回给客户 if not len(data): break clientsock.sendall(data) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() #close the connection try: clientsock.close() except KeyboardInterrupt: raise except: traceback.print_exc()
客户端测试: [[email protected] one]# telnet localhost 51422 Trying ::1... telnet: connect to address ::1: Connection refused Trying 127.0.0.1... Connected to localhost. Escape character is ‘^]‘. wang wang wang wang tian tian xiang xiang shang shang hao hao
客户端响应服务器的例子:
#!/usr/bin/env python #-*- coding:utf-8 -*- import socket, sys port = 51422 host = "localhost" data = "x" * 10485760 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = s.connect((host, port)) bytestwritten = 0 while bytestwritten <= len(data): startpos = bytestwritten endpos = min(bytestwritten + 1024 ,len(data)) bytestwritten += s.send(data[startpos:endpos]) //感觉这点有一个问题 sys.stdout.write("Wrote %d bytes\r" % bytestwritten) sys.stdout.flush() s.shutdown() print "All data sent" while 1: buf = s.recv(1024) if not len(buf): break sys.stdout.write(buf)
启动服务器,接着运行响应服务器。服务器将显示有来自客户端的连接。客户端试图发送一个10Mb的数据,以1KB为单位传到服务器,接着它会取回结果。
10MB数据永远也传送不完。服务器会读取开始的4KB,试图在写完之后重复这个过程。因为客户端在发送完所有数据之前根本不进行任何的操作,操作系统的传输buffer在某一点上就会充满,两个进程就会在send()函数停滞。
时间: 2024-10-27 13:15:40