server
#服务端
import socket
phone = socket.socket()
phone.bind(('127.0.0.1',8848))
print('服务器启动成功!等待用户连接....')
phone.listen(5)
while 1:
conn, addr = phone.accept()
print(f'{addr}连接成功......')
while 1:
try:
name = conn.recv(1024).strip().decode("utf-8")
print(f'来自{addr}的消息:{name}')
if name.upper() == 'Q':
print(f'{addr}退出程序!')
break
conn.send(name.encode('utf-8'))
except EnvironmentError:
print('客户端异常退出程序!')
break
conn.close()
phone.close()
client
#客户端
import socket
phone = socket.socket()
phone.connect(('127.0.0.1',8848))
while 1:
data = input('>>>:').strip()
if not data:
print('输入的内容不能为空!')
continue
if data.upper() == 'Q':
phone.send(data.encode('utf-8'))
print("退出程序!")
break
phone.send(data.encode('utf-8'))
print(phone.recv(1024).strip().decode('utf-8'))
phone.close()