聊天室
服务端
import socket
from threading import Thread
server = socket.socket()
server.bind(('127.0.0.1', 1688))
server.listen(5)
def send_msg(c, addr):
while True:
msg = input(f'
发消息给{addr}>>>')
c.send(msg.encode('utf8'))
def recv_msg(c, addr):
while True:
try:
msg = c.recv(1024)
print(f'
收到{addr}的消息:', msg.decode('utf8'))
except Exception as e:
print(f'{c}断开')
c.close()
break
print('启动')
while True:
c, addr = server.accept()
print(f'{c}进入连接!')
try:
# 分别创建2个线程,一个接消息,一个发消息
t1 = Thread(target=send_msg, args=(c, addr))
t2 = Thread(target=recv_msg, args=(c, addr))
# 将两个线程分别启动
t1.start()
t2.start()
except Exception as e:
print(e)
客户端
import socket
from threading import Thread
clien = socket.socket()
flag = clien.connect(('127.0.0.1', 1688))
def send_msg(client):
while True:
msg = input('>>>>>')
client.send(msg.encode('utf8'))
def recv_msg(client):
while True:
msg = clien.recv(1024)
print(f'{flag}', msg.decode('utf8'))
# 分别创建2个线程,一个接消息,一个发消息
t1 = Thread(target=send_msg, args=(clien,))
t2 = Thread(target=recv_msg, args=(clien,))
# 将两个线程分别启动
t1.start()
t2.start()