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!")


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值