python核心编程:单进程服务器非堵塞模式

服务器

#-*-coding:utf-8-*-
from socket import *
import time
g_socketlist = []
def main():
    s = socket(AF_INET,SOCK_STREAM)
    s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)#防止出现端口被占用的异常
    addr = ("",7878)
    s.bind(addr)
    s.listen(5)
    s.setblocking(False)#关闭堵塞
    while True:
        try:
            newClient = s.accept()
        #except Exception as result:
        except:
            pass
        else:
            print "一个客户端上线:",str(newClient)
            newClient[0].setblocking(False)
            g_socketlist.append(newClient)
        needDelClient = []
        for clientSocket,clientAddr in g_socketlist:
            try:
                recvData = clientSocket.recv(1024)
                if len(recvData) > 0:
                    print "recv[%s]:%s"%(str(clientAddr),recvData)
                else:
                    print "recv[%s]客户端已关闭"%str(clientAddr)
                    clientSocket.close()
                    needDelClient.append((clientSocket,clientAddr))
            #except Exception as result:
            except:
                pass
        for needDel in needDelClient:
            g_socketlist.remove(needDel)

if __name__ == '__main__':
    main()

客户端

#-*-coding:utf-8-*-
from socket import *
import random
import time

serverIp = raw_input("请输入服务器的ip:")
connNum = raw_input("请输入要链接服务器的次数(例如1000):")
g_socketList = []
for i in range(int(connNum)):
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((serverIp, 7878))
    g_socketList.append(s)
    print(i)

while True:
    for s in g_socketList:
        s.send(str(random.randint(0,100)))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值