目的
在PC上交叉编译好的文件要传输的开发板,用u盘的话太麻烦
PC使用的语言python,开发板使用的是c++
通过wifi建立socket通信,PC作为server,开发板作为client
PC端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import socket
def send_file(filename):
hostname = '192.168.31.177' # socket server IP
port = 8998 # socket 端口号
with open(filename, 'rb') as f:
file_data = f.read()
s = socket.socket()
s.bind((hostname, port))
print("File read completed, waiting for connection and transfer")
s.listen(1)
conn, addr = s.accept()
conn.sendall(file_data)
conn.close()
s.close()
print("done")
# usage
send_file('xxx')
|
开发板端
准备好一个 config.conf 文件,用来存储 pc 的 ip 和 port , 程序将从这个文件读取pc的相关信息。文件内容形如
pc_ip=xxx.x.x.x
pc_port=xxx
编写c++ socket client,在传输完文件后,更改该文件的权限,这里使用了 chmod
将文件改成 S_IRWXU
可读,可写,可执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
#include <iostream>
#include <fstream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include "stdio.h"
#include <sys/stat.h>
using std::string;
using std::cout;
using std::endl;
using std::ifstream;
void send_file(const char* filename, string host, int port) {
int client_fd = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(host.c_str());
address.sin_port = htons(port);
connect(client_fd, (sockaddr*)&address, sizeof(address));
std::ofstream output_file(filename);
char buffer[1024];
ssize_t bytes_received;
while ((bytes_received = recv(client_fd, buffer, sizeof(buffer), 0)) > 0) {
output_file.write(buffer, bytes_received);
}
cout << "recv done! "<< endl;
chmod(filename, S_IRWXU);
cout << "Modified file permissions done! "<< endl;
close(client_fd);
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " FILENAME\n";
return 1;
}
/* 读取 PC 端的IP和port */
int port;
string ip;
ifstream configFile("config.conf");
if (configFile.is_open()) {
string line;
while (getline(configFile, line)) {
if (line.find("pc_ip") != string::npos) {
size_t pos = line.find("=");
ip = line.substr(pos + 1);
}
if (line.find("pc_port") != string::npos) {
size_t pos = line.find("=");
port = stoi(line.substr(pos + 1));
}
}
configFile.close();
} else {
cout << "Unable to open file"<<endl;
}
send_file(argv[1], ip, port);
}
|
使用
- PC和开发板连接到同一wifi
- PC端,改好PC在wifi下的ip,所使用的端口,以及要传输的文件名(待传输文件与该py文件同目录),运行py文件
- 开发板端运行编译好的c++,跟上文件名参数,如./client xxx 其中xxx是保存后文件名
- 等待接收完毕
所传文件长度不限,并且如果已存在会覆盖写入