python简单的多人聊天室
短信预约 -IT技能 免费直播动态提醒
刚开始学习python,写了一个聊天室练练手。
Server.py
import socket,select,thread;
host=socket.gethostname()
port=5963
addr=(host,port)
inputs=[]
fd_name={}
def who_in_room(w):
name_list=[]
for k in w:
name_list.append(w[k])
return name_list
def conn():
print 'runing'
ss=socket.socket()
ss.bind(addr)
ss.listen(5)
return ss
def new_coming(ss):
client,add=ss.accept()
print 'welcome %s %s' % (client,add)
wel='''welcome into the talking room .
please decide your name.....'''
try:
client.send(wel)
name=client.recv(1024)
inputs.append(client)
fd_name[client]=name
nameList="Some people in talking room, these are %s" % (who_in_room(fd_name))
client.send(nameList)
except Exception,e:
print e
def server_run():
ss=conn()
inputs.append(ss)
while True:
r,w,e=select.select(inputs,[],[])
for temp in r:
if temp is ss:
new_coming(ss)
else:
disconnect=False
try:
data= temp.recv(1024)
data=fd_name[temp]+' say : '+data
except socket.error:
data=fd_name[temp]+' leave the room'
disconnect=True
if disconnect:
inputs.remove(temp)
print data
for other in inputs:
if other!=ss and other!=temp:
try:
other.send(data)
except Exception,e:
print e
del fd_name[temp]
else:
print data
for other in inputs:
if other!=ss and other!=temp:
try:
other.send(data)
except Exception,e:
print e
if __name__=='__main__':
server_run()
client.py
import socket,select,threading,sys;
host=socket.gethostname()
addr=(host,5963)
def conn():
s=socket.socket()
s.connect(addr)
return s
def lis(s):
my=[s]
while True:
r,w,e=select.select(my,[],[])
if s in r:
try:
print s.recv(1024)
except socket.error:
print 'socket is error'
exit()
def talk(s):
while True:
try:
info=raw_input()
except Exception,e:
print 'can\'t input'
exit()
try:
s.send(info)
except Exception,e:
print e
exit()
def main():
ss=conn()
t=threading.Thread(target=lis,args=(ss,))
t.start()
t1=threading.Thread(target=talk,args=(ss,))
t1.start()
if __name__=='__main__':
main()
运行时先启动服务端。进入聊天室先起一个昵称。服务端会向客户端发送当前聊天室内聊天人的列表。一个客户端发出的消息会通过服务端发给其他客户端。
效果如下:
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341