Client 树莓派 4B 2G 运行 debian 11 x64 Server Macbook macOS 两者采用有线连接至同一台交换机中
在传输文件时有时成功,有时失败。失败时在终端打印乱码,但对于同一文件打印出来的乱码相同,个人猜测是编码问题,但是 debian 和 macOS 用的应该都是 UTF-8 ?而且传字符串没有问题
下面给出 Server 端和 Client 端的代码
//Server 接收端
struct PacketHeader {
int size; // 大小:字节
PacketHeader() {
size = 0;
}
};
void *receiveMsg(void *sock) {
// system("pwd");
char buffer[1024];
int *socket = (int *) sock;
while (1) {
usleep(500);
int nRecv = recv(*socket, buffer, 1024, 0);
if (nRecv <= 0) {
continue;
} else if (nRecv == sizeof(PacketHeader)) {
PacketHeader ph;
memcpy(&ph, buffer, nRecv);
cout << "大小:" << ph.size << "Bytes" << endl;
string filename = ("../Received/" + getCurrentTime() + ".jpg");
FILE *fp = fopen(filename.c_str(), "wb");
if (fp == NULL) {
cout << "file not found" << endl;
}
cout << "开始接收图片" << endl;
nRecv = 0;
while (nRecv < ph.size) {
usleep(500);
memset(buffer, 0, sizeof(buffer));
int byteCount = recv(*socket, buffer, 1024, 0);
if (byteCount <= 0) {
continue;
}
fwrite(buffer, 1, byteCount, fp);
nRecv += byteCount;
cout << "已接收 " << nRecv << " Bytes" << endl;
}
cout << "共接收 " << nRecv << " Bytes" << endl;
fclose(fp);
} else {
buffer[nRecv] = '\0';
cout << buffer << endl;
}
}
# Client 发送端
struct PacketHeader
{
int size; // 大小:字节
PacketHeader()
{
size = 0;
}
};
void *sendMsg(void *socket)
{
int sock = *((int *)socket);
while (1)
{
char msg[4096];
string filename;
cin >> filename;
FILE *fp = fopen(("../image/" + filename).c_str(), "rb");
if (fp == NULL)
{
cout << "file not found" << endl;
continue;
}
int sz = FileSize(("../image/" + filename).c_str());
cout << "文件打开成功,大小:" << sz << " Bytes" << endl;
PacketHeader ph;
ph.size = sz;
send(sock, (const char *)&ph, sizeof(ph), 0);
cout << "已发送头部信息" << endl;
int nSend = 0;
char buffer[1024];
while(nSend < sz)
{
int nBytes = fread(buffer, sizeof(char), sizeof(buffer), fp);
if (nBytes <= 0)
break;
send(sock, buffer, nBytes, 0);
cout << "已发送 " << nBytes << " Bytes" << endl;
nSend += nBytes;
}
cout<<"总计发送 "<<nSend<<" Bytes"<<endl;
fclose(fp);
cout << "successfully send " + filename << endl;
}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.