从(纯文本)流套接字到可以发送文件的“东西”,我遇到了一个小问题。一个月前,我写了一个基本的聊天客户端。现在我希望能够发送和接收任何类型的文件。让我们使用 PDF 或图像。我将列出我正在使用的资源,以及我“认为”的正确方向。我只需要帮助连接点。
从我的研究看来,我需要先获取文件,将其转换为二进制文件,然后将其发送到 . 我猜我想要一种 TCP 风格,因为我非常关心文件的数据包是否按顺序/完全出现。
我读过关于套接字的 Beej.us。我也没有找到发送数据的部分。我确实找到了关于发送不同“数据类型”的部分,即浮点数等。
我猜我想要一个“数据报”而不是流。如果有人知道本书中的部分,我确实有我的 Unix Networking Programming 的副本。我找不到一个看起来像 . 经过 2、3 个小时的研究,我真的找不到任何简单或清晰的东西。大多数只是未回答的论坛问题..
这就是我要开始的。后来我会用自定义IP、端口等来改变它。从Beej获取数据报-发送者。从命令行参数发送文本..
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define SERVERPORT "4950" // the port users will be connecting to
int main(int argc, char *argv[])
{
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
if (argc != 3) {
fprintf(stderr,"usage: talker hostname message\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM; // datagrams..
if ((rv = getaddrinfo(argv[1], SERVERPORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket.
//I'm not sure about the need for a loop
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
// here is where we would send a file. Lets say ./img.png
// If I had to guess I'd need to write a custom packet, turn the file into binary, then to
//a packet. Then call send while we still have packets.
// Am I on the right track?
if ((numbytes = sendto(sockfd, argv[2], strlen(argv[2]), 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
freeaddrinfo(servinfo);
printf("talker: sent %d bytes to %s\n", numbytes, argv[1]);
close(sockfd);
return 0;
}