标签:coding 数据 reading bsp listen finally while 共享 链接
from socket import * serSocket = socket(AF_INET, SOCK_STREAM) # 重复使用绑定的信息 serSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR , 1) localAddr = (‘‘, 7788) serSocket.bind(localAddr) serSocket.listen(5) while True: print(‘-----主进程,,等待新客户端的到来------‘) newSocket,destAddr = serSocket.accept() print(‘-----主进程,,接下来负责数据处理[%s]-----‘%str(destAddr)) try: while True: recvData = newSocket.recv(1024) if len(recvData)>0: print(‘recv[%s]:%s‘%(str(destAddr), recvData)) else: print(‘[%s]客户端已经关闭‘%str(destAddr)) break finally: newSocket.close() serSocket.close()
当服务器为一个客户端服务时,而另外的客户端发起了connect,只要服务器listen的队列有空闲的位置,就会为这个新客户端进行连接,并且客户端可以发送数据,但当服务器为这个新客户端服务时,可能一次性把所有数据接收完毕
from socket import * from multiprocessing import * from time import sleep # 处理客户端的请求并为其服务 def dealWithClient(newSocket,destAddr): while True: recvData = newSocket.recv(1024) if len(recvData)>0: print(‘recv[%s]:%s‘%(str(destAddr), recvData)) else: print(‘[%s]客户端已经关闭‘%str(destAddr)) break newSocket.close() def main(): serSocket = socket(AF_INET, SOCK_STREAM) serSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR , 1) localAddr = (‘‘, 7788) serSocket.bind(localAddr) serSocket.listen(5) try: while True: print(‘-----主进程,,等待新客户端的到来------‘) newSocket,destAddr = serSocket.accept() print(‘-----主进程,,接下来创建一个新的进程负责数据处理[%s]-----‘%str(destAddr)) client = Process(target=dealWithClient, args=(newSocket,destAddr)) client.start() #因为已经向子进程中copy了一份(引用),并且父进程中这个套接字也没有用处了 #所以关闭 newSocket.close() finally: #当为所有的客户端服务完之后再进行关闭,表示不再接收新的客户端的链接 serSocket.close() if __name__ == ‘__main__‘: main()
#coding=utf-8 from socket import * from threading import Thread from time import sleep # 处理客户端的请求并执行事情 def dealWithClient(newSocket,destAddr): while True: recvData = newSocket.recv(1024) if len(recvData)>0: print(‘recv[%s]:%s‘%(str(destAddr), recvData)) else: print(‘[%s]客户端已经关闭‘%str(destAddr)) break newSocket.close() def main(): serSocket = socket(AF_INET, SOCK_STREAM) serSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR , 1) localAddr = (‘‘, 7788) serSocket.bind(localAddr) serSocket.listen(5) try: while True: print(‘-----主进程,,等待新客户端的到来------‘) newSocket,destAddr = serSocket.accept() print(‘-----主进程,,接下来创建一个新的进程负责数据处理[%s]-----‘%str(destAddr)) client = Thread(target=dealWithClient, args=(newSocket,destAddr)) client.start() #因为线程中共享这个套接字,如果关闭了会导致这个套接字不可用, #但是此时在线程中这个套接字可能还在收数据,因此不能关闭 #newSocket.close() finally: serSocket.close() if __name__ == ‘__main__‘: main()
标签:coding 数据 reading bsp listen finally while 共享 链接
原文地址:https://www.cnblogs.com/leecoffee/p/9035540.html