python 通过UDP传输文件

使用一个简单的python脚本将一个本地文件以码流的形式,通过UDP协议发送到对端:
import socket
import os
import stat
import struct
 
MAX_PACK_SIZE = 100
DEST_IP = 'localhost'
DEST_PORT = 17800
 
filename = 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]
上一篇:《谁是MVP》直播系列——想听什么,你说!


下一篇:ML之Clustering之K-means:K-means算法简介、应用、经典案例之详细攻略(二)