服务端:socket_server.py
import socket
# 创建socket对象
sock = socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)
# 绑定地址
sock.bind(("",8000))
# 设置监听队列长度
sock.listen(5)
# 两个变量接收两个返回值(接收方法:会返回一个新的客户端的socket对象和客户端的ip和端口)
con,add = sock.accept()
# 循环发送,接收数据
while True:
if con:
# 以每次512字节方式接收客户端的数据
content = con.recv(512)
# 解码,打印客户端内容
print(content.decode())
# 将输入数据编码为字节码,存储到变量中
send_data = input(">>>").encode()
# 发送给客户端
con.send(send_data)
else:
print("客户端断开连接")
# 关闭socket
sock.close()
客户端:socketClient.py
#!/usr/bin/python3
#coding:utf-8
import socket
sock = socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)
sock.connect(("10.10.21.16",8000))
while True:
send_data = input(">>>").encode()
sock.send(send_data)
content = sock.recv(512)
print(content.decode())
sock.close()