python socket多人聊天室

服务端可以接受多个客户端连接

客户端,服务端可以进行双向通信,双向发信息。

采用select函数,实现多客户连接.

server.py:

import socket,select,sys

host="0.0.0.0"
port=7777

sfd=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sfd.bind((host,port))
print "HELLO BOY,I'm SERVER\nput in '88' to leave me!"
sfd.listen(10)
print "NOW I'm SRART LISTEN......"


clientlist=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]#10 ge -1
currentplace=0




while 1:
	carefd=[0,sfd.fileno()]
	for membe in clientlist:
		if membe!=-1:
			#membe.fileno()
			carefd.append(membe.fileno())			
	infds,outfds,errfds=select.select(carefd,[],[],999)
	if len(infds)!=0:
		for membe in infds:
			if membe==sfd.fileno():
				newclientsock,newclientaddr=sfd.accept()
				clientlist[currentplace]=newclientsock
				currentplace+=1
			elif membe==0:
				#print ("55\n")
				tosend=sys.stdin.readline()
				if tosend=="88\n":
					sfd.close()
					sys.exit()
				for allclient in clientlist:
					if allclient!=-1:
						allclient.send(tosend)
				print("Send To ALL Client Succeed!->"),(tosend),
			else :
				for allclient in clientlist:
					if allclient!=-1:
						if membe==allclient.fileno():
							torecv=allclient.recv(100)
							if torecv=="":
								print "!!!!!!a client drop!!!!!!"
								clientlist.remove(allclient)
								currentplace-=1
							else:
								print "receive->",(torecv),
	else:
		print("999 second passed!nothing happened!")	

client.py:

import socket,select,sys

host="127.0.0.1"
port=7777

sfd=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "HELLO BOY ,I'm CLIENT"
sfd.connect((host,port))
sfd.send("hello server!")
print "NOW SERVER  IS LINKED OK......"

while 1:
	infds,outfds,errfds=select.select([sfd.fileno(),0],[],[],999)
	if len(infds)!=0:
		for membe in infds:
			if membe==sfd.fileno():
				buf=sfd.recv(100)
				if buf=="":
					print "server cutted"
					sys.exit()
				else:
					print "receive->",(buf),
				
					
				
			if membe==0:
				#print ("inin\n")
				tosend=sys.stdin.readline()				
				sfd.send(tosend)
				print "send ok!->",tosend,
				
		

		
		
	else:
		print("999 second passed!no things happen!")


你可能感兴趣的:(socket)