时间:2020-08-13 python教程 查看: 765
本文实例为大家分享了Python基于Socket实现简单聊天室,供大家参考,具体内容如下
服务端
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/27 15:34
# @File : Server.py
"""
聊天室服务端
"""
import socket,select
host=''
port=7799
addr=(host,port)
inputs=[]
members={}
#配置服务端
def start_Server():
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(addr)
server.listen(5)
return server
#返回聊天室成员列表
def show_members(w):
name_list=[]
for i in w:
name_list.append(w[i])
return name_list
#处理新的成员
def new_member(server):
client,addr=server.accept()
print('欢迎进入聊天室 ,%s,%s' % (client,addr))
try:
client.send('请输入名字')
name=client.recv(1024)
inputs.append(client)
members[client]=name
names='其它用户%s'% (show_members(members))
client.send(names)
except Exception,e:
print(e)
#正式启动服务端
def server_run():
server=start_Server()
print 'start'
inputs.append(server)
while True:
rs,ws,es=select.select(inputs,[],[])
for temp in rs:
if temp is server:
new_member(temp)
else:
disConnect=False
try:
data=temp.recv(1024)
data=members[temp]+'说'+data
except socket.error:
data=members[temp]+'离开'
disConnect=True
if disConnect:
inputs.remove(temp)
print data
for other in inputs:
if other!=server and other!=temp:
try:
other.send(data)
except Exception,e:
print(e)
del members[temp]
else:
print data
for other in inputs:
if other!=server and other!=temp:
try:
other.send(data)
except Exception,e:
print(e)
if __name__ == '__main__':
server_run()
客户端
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/27 15:34
# @File : Client.py
"""
聊天室客户端
"""
import socket
import select
import threading
host='127.0.0.1'
port=7799
addr=(host,port)
#配置连接
def connect():
client=socket.socket()
client.connect(addr)
return client
#显示用户列表
def show_member(s):
my=[s]
while True:
rs,ws,es=select.select(my,[],[])
if s in rs:
try:
print s.recv(1024)
except socket.error:
print 'socket is error'
exit()
#进行对话
def talk(s):
while True:
try:
info=raw_input('>>>')
except Exception:
print 'can\'t input'
exit()
try:
s.send(info)
except Exception,e:
print e
exit()
#主函数
def main():
client=connect()
t=threading.Thread(target=show_member,args=(client,))
t.start()
t1=threading.Thread(target=talk,args=(client,))
t1.start()
if __name__ == '__main__':
main()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。