服务端
import socket
server = socket.socket() #生成套接字对象
server.bind(('0.0.0.0', 8000)) #套接字绑定ip和端口,变为监听套接字
server.listen(5) #开始监听
while True:
conn, addr = server.accept() #建立连接,生成对等套接字
print('用户连接:', addr)
while True:
try:
data = conn.recv(1024)
if data == b'Q' or data == b'q':
print('用户退出:', addr)
break
else:
print('收到的消息:', data.decode())
conn.send(data)
except Exception as e:
print(e)
conn.close()
break
import socket
server = socket.socket() #生成套接字对象
server.bind(('0.0.0.0', 8000)) #套接字绑定ip和端口,变为监听套接字
server.listen(5) #开始监听
while True:
conn, addr = server.accept() #建立连接,生成对等套接字
print('用户连接:', addr)
while True:
try:
data = conn.recv(1024)
if data:
print('收到的消息:', data.decode())
conn.send(data)
else:
print('用户退出:', addr)
conn.close()
break
except Exception as e:
print(e)
print('用户退出:', addr)
conn.close()
break
客户端
import socket
client = socket.socket()
client.connect(('127.0.0.1',8889))
while True:
data = input('输入数据:')
if data:
client.send(data.encode())
recv_data = client.recv(1024)
print(recv_data.decode())
else:
break
client.close()