应用:模拟QQ聊天
服务器参考代码
import socket
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
address = ('', 8000)
server_sock.bind(address)
server_sock.listen(128)
while True:
client_sock, client_addr = server_sock.accept()
print("与客户端%s:%s建立了连接" % client_addr)
while True:
recv_data = client_sock.recv(1024)
if len(recv_data) > 0:
print("客户端说:%s" % recv_data.decode())
msg = input("请输入回复的内容:")
client_sock.send(msg.encode())
else:
break
print("客户端%s:%s已下线" % client_addr
)
client_sock.close()
server_sock.close()
客户端参考代码
import socket
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_addr = ('127.0.0.1', 8000)
client_sock.connect(server_addr)
while True:
msg = input("请输入要发送的消息:")
if len(msg) > 0:
client_sock.send(msg.encode())
recv_data = client_sock.recv(1024)
print("收到的消息:%s" % recv_data.decode())
else:
break
client_sock.close()