使用Socket 编程 完成的一个简单的传送文件的工具,
却一直报错。
在网上查了知道,Python 2.6以后的版本,tkFileDialog.askopenfilenames
返回的居然是字符串
原文:http://cndenis.iteye.com/blog/1754907
稍稍修改Fileopen部分 就搞定
def FileOpen():
r = tkFileDialog.askopenfilename(title = u'打开'.encode('utf-8'),
filetypes=[('All files', '*')] )
filename=r.split(r'/')
print type(filename[-1]) #unicode
client(str(filename[-1])) #str
程序send端程序如下:
# -*- coding: gbk -*-
from Tkinter import *
import tkFileDialog
import socket
import struct
import os
def client(filename):
host = '192.168.93.1'
port = 34587
buf_size = 1024
addr =(host, port)
#pic_file_size = struct.calcsize('128s32sI8s')
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(addr)
file_head = struct.pack('128s11I', filename, 0, 0, 0, 0, 0, 0, 0, 0, os.stat(filename).st_size, 0, 0)
#发送文件信息
client_socket.send(file_head)
#发送文件内容
pic_fobj = open(filename, 'rb')
while True:
file_data = pic_fobj.read(buf_size)
if not file_data:
break
client_socket.send(file_data)
pic_fobj.close()
client_socket.close()
def FileOpen():
r = tkFileDialog.askopenfilename(title = u'打开'.encode('utf-8'),
filetypes=[('All files', '*')] )
filename=r.split(r'/')
print type(filename[-1])
client(str(filename[-1]))
root = Tk()
root.title(u'文件发送'.encode('utf-8'))
root.geometry('400x200')
button1 = Button(root, text = 'File Open', height=2,width=6,bg='gray',
command = FileOpen)
button1.pack(expand=YES, fill=BOTH)
root.mainloop()