服务器
#-*-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)))