亲宝软件园·资讯

展开

python文件传输 python3.5基于TCP实现文件传输

09w09 人气:0

服务器代码

# _*_ coding:utf-8 _*_

from socket import *
import _thread

def tcplink(skt,addr):
 print(skt)
 print(addr,"已经连接上...")
 print('开始发送文件')
 with open('./ww.jpg', 'rb') as f:
  for data in f:
   print(data)
   skt.send(data)
 f.close()
 skt.close()


HOST = "127.0.0.1"
PORT = 23333
ADDR = (HOST,PORT)

server = socket(AF_INET,SOCK_STREAM)
server.bind(ADDR)
server.listen(5)

while True:
 print("等待连接...")
 skt,addr = server.accept()
 print(skt)
 try:
  _thread.start_new_thread(tcplink,(skt,addr))
 except:
  print("线程无法启动")
server.close()

客户端代码

# _*_ utf-8 _*_

from socket import *

HOST = "127.0.0.1"
PORT = 23333
ADDR = (HOST,PORT)

client = socket(AF_INET,SOCK_STREAM)
client.connect(ADDR)

with open("./gg.jpg","ab") as f:
 while True:
  data = client.recv(1024)
  if not data:
   break;
  f.write(data)

f.close()
print("接收完毕")
client.close()

上面的代码都经过测试能正常运行,希望大家能有所启发。

加载全部内容

相关教程
猜你喜欢
用户评论