Python TCP接收/发送信息

Python TCP接收/发送信息

@ Time: 2021/12/30
@ Author: 迈向明天
@ File:客户端-编码.py
@ Software: PyCharm

import socket
import os

path = “D:\Desktop\TestRead\” # 文本文档路径
file_list = [path + i for i in os.listdir(path)] # 遍历文件夹中文本文档
print(file_list)

for text_file in file_list:
tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 1、初始化套接字
tcp_socket.connect((“IP”,8021)) # 2、建立链接他,要传入链接的服务器 IP 和 Port

file = text_file.split("\\")[3] # 切片,只选路径最后的文本文档
text_file = open(text_file,"r")
text_ReadContent = text_file.read() # 读

tcp_socket.send((text_ReadContent.encode("UTF-8")) # 3、发送数据
print("开始发送")

data = tcp_socket.recv(1024) # 接收数据 recv → 指定数据缓冲区的大小
tcp_socket.close() # 5、断开

print("开始接收")
print(data.decode(UTF-8))

filename = file.split(".")[0] + "-识别文件" + ".txt" # 读文件切片,可选
print(filename)

text_Write = open("D:\\Desktop\\TestRead\\" + filename,"w") # 读
text_WriteContent = text_WriteOpen.write(str(data)  #数据转为字符串类型

你可能感兴趣的:(tcp/ip,python,网络)