马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
使用 Socket 做的一个聊天室,分为客户端和服务端。
废话不多说,直接上代码:
客户端( Client.py ):import socket
import threading as td
outString = ''
inString = ''
def client_send(client):
global outString
while True:
string = '%s : %s' % (nick, input())
client.send(string.encode('utf-8'))
def client_accept(client):
global inString
while True:
try:
inString = client.recv(1024)
if not inString:
break
if outString != inString:
print(outString)
except:
break
nick = input('请输入你的昵称:')
ip = input('请输入您的 IP:')
port= 8888
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((ip, port))
client.send(nick.encode('utf-8'))
td.Thread(target=client_send, args=(client, )).start()
td.Thread(target=client_accept, args=(client, )).start()
服务端( Server.py ):import socket
import threading as td
people = 0
# 接受
def clientIn(conn, nick):
global data, people
while True:
try:
temp = conn.recv(1024)
if not temp:
conn.close()
return
NotifyAll(temp)
print(data.decode('utf-8'))
except:
NotifyAll(nick.decode('utf-8') + '断开连接!')
people -= 1
print(data)
return
def NotifyAll(ss):
global data
if con.acquire():
data = ss
con.release()
con = td.Condition()
host = input('请输入服务器的IP地址:')
port = 8888
data = ''
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(1)
print('服务器已创建')
while True:
conn, addr = server.accept()
nick = conn.recv(1024)
NotifyAll('欢迎' + nick.decode('utf-8') + ' 到聊天群!')
people += 1
print(data)
print('当前房间有' + str(people) + '人')
conn.send(data.encode('utf-8'))
td.Thread(target=clientIn, args=(conn, nick)).start()
演示:
|