承接上篇,TCP/IP可靠性传输,关注的更多的是数据完整性这类数据质量的问题。会用断点续传、文件等方式来容错。
本文只是基础篇,简单的阐述一下客户端的实现。
python客户端的实现就4步:
1.创建实例
2.连接端口 connect(,)
3.发送命令 send("")
4.关闭端口 close()
import socket
import sys
def socketClientTest():
myclient = socket.socket() #1.创建
myclient.connect(("localhost",9998)) #2.连接
##############################################3.发送数据
while True:
msg = input(">>:").strip() #
if len(msg) == 0: continue
myclient.send(msg.encode("utf-8")) #3.1发:msg
res_return = myclient.recv(1024) #3.2 收:返回数据
print("getting res_return , ", res_return)
total_rece_size = int(res_return)
print("total return size:", res_return)
myclient.send("准备好接收了,发吧".encode("utf-8")) #3.3 发:确认可收数据
received_size = 0
cmd_res = b''
f = open("test_copy.html", "wb") # 收到的数据存文件
while received_size != total_rece_size: # 代表还没收完
data = myclient.recv(1024) #3.4 收
received_size += len(data) #
cmd_res += data
else:
print("数据收完了", received_size)
f.write(cmd_res) # 把接收到的结果存下来,一会看看收到的数据 对不对
##############################################
myclient.close() #4.关闭
def main():
print("socketClientTest")
socketClientTest()
if __name__ == '__main__':
main()