python 通过 UDP 传输文件
import socket
import os
import stat
import structMAX_PACK_SIZE = 100
DEST_IP = 'localhost'
DEST_PORT = 17800filename = raw_input("input filename")
filesize = os.stat(filename)[stat.ST_SIZE]
f = open(filename, "rb")
chList = []
for i in range(0, filesize):
(ch,) = struct.unpack("B", f.read(1))
chList.append(ch)client = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
packSize = 0
string = ""
args = []
for i in range(0, filesize):
packSize = packSize + 1
string = string + struct.pack("B", chList[i])
if (MAX_PACK_SIZE == packSize or i == filesize - 1):
client.sendto(string, (DEST_IP, DEST_PORT))
packSize = 0
string = ""
client.close()
使用到的知识点:
1、UDP客户端最简单的实现:
client = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
client.sendto(string, (DEST_IP, DEST_PORT))
client.close()
2、python中对码流的操作:struct.pack 和 struct.unpack的使用
(ch,) = struct.unpack("B", f.read(1))
string = string + struct.pack("B", chList[i])
3、二进制文件的读取:
f = open(filename, "rb")
4、获得系统中某个文件的字节数
filesize = os.stat(filename)[stat.ST_SIZE]
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。