# -*- coding: utf-8 -*-
import Tkinter
import tkFileDialog
from socket import *
import struct
import os
def client(filename):
Addr=('127.0.0.1',8000)
BUFSIZE=2048
Sendsocket=socket(AF_INET,SOCK_STREAM)
Sendsocket.connect(Addr)
FileHead=struct.pack('128s11i',filename,0,0,0,0,0,0,0,0,os.stat(filename).st_size,0,0)
Sendsocket.send(FileHead)
fp=open(filename,'rb')
while 1:
FileData=fp.read(BUFSIZE)
if not FileData:
break
Sendsocket.send(FileData)
fp.close()
Sendsocket.close()
def FileOpen():
r = tkFileDialog.askopenfilename(title = 'Python Tkinter',
filetypes=[('All files', '*')] )
filename=r.split('/')
client(filename[-1])
root = Tkinter.Tk()
button1 = Tkinter.Button(root, text = 'File Open', height=8,width=14,bg='blue',
command = FileOpen)
button1.pack()
root.mainloop()
#接收端
# -*- coding: utf-8 -*-
from socket import *
import os
import struct
Addr=('127.0.0.1',8000)
BUFSIZE=1024
FileInfoSize=struct.calcsize('128s32sI8s')
SocketRecv=socket(AF_INET,SOCK_STREAM)
SocketRecv.bind(Addr)
SocketRecv.listen(5)
print "waitting ........"
conn,addr=SocketRecv.accept()
print "send from" ,addr
FileHead=conn.recv(FileInfoSize)
filename,temp1,filesize,temp2=struct.unpack('128s32sI8s',FileHead)
print filename,len(filename),type(filename)
print filesize
filename='new_'+filename.strip('\00')
fp = open(filename,'wb')
restsize=filesize
while 1:
if restsize<BUFSIZE:
filedata=conn.recv(restsize)
else:
filedata=conn.recv(BUFSIZE)
if not filedata:
break
fp.write(filedata)
restsize=restsize-len(filedata)
if restsize==0:break
fp.close()
conn.close()
SocketRecv.close()
print 'Finished !!!'
import socketimport struct
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 10000))
values = (1, 'ab', 2.7)
packer = struct.Struct('I 2s f')
packed_data = packer.pack(*values)
try:
sock.sendall(packed_data)
finally:
sock.close()
有个模块叫struct,可以自定义结构体,可以这样发送代码。
try:import cPickle as pickle
except:
import pickle
class AA():
def a(self):
print "123"
ddd = AA()
data = pickle.dumps(ddd)
还有个模块叫pickle,可以打包任何python对象,打包的结果也可以拿到套接字里发。
通过数据传输发送。socket是python自带的包,是应用层与TCP或IP协议通信的中间软件抽象层,pythonsocket可以通过数据传输发送浮点型数据。浮点型数据分为浮点型常量和浮点型变量,浮点型常量,实型也称为浮点型,实型常量也称为实数或者浮点数。欢迎分享,转载请注明来源:内存溢出
评论列表(0条)