服务端Server.py代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# @Time : 2018/5/18 16:05
# @Desc : 群聊服务端
# @File : Server.py
# @Software: PyCharm
import socket, select
host = socket.gethostname()
port = 5999
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 "服务端开始运行"
ss = socket.socket()
ss.bind(addr)
ss.listen(5)
return ss
"""
添加新的群成员
"""
def new_coming(ss):
client, add = ss.accept()
print '欢迎 %s %s' % (client, add)
wel = '''欢迎进入聊天室 . 请输入你的名字:'''
try:
client.send(wel)
name = client.recv(1024)
inputs.append(client)
fd_name[client] = name
nameList = "已在线聊天的群成员是 %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] + " 说 : "+ data
except socket.error:
data = fd_name[temp] + "离开聊天室"
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代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# @Time : 2018/5/18 16:06
# @Desc : 群聊客户端
# @File : Client.py
# @Software: PyCharm
import socket, select, threading
host = socket.gethostname()
addr = (host, 5999)
"""
连接
"""
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 "通信出现异常"
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()
先启动服务端代码,后启动客户端(启动一个,代表一个群成员,可多个)代码,执行结果如下: