TCP套接字,发送文件,客户端服务器,服务器不保存整个文件,C语言



我写了一个简单的协议,其中Im能够在客户端和服务器之间交换文件/文本消息。如果客户端向服务器发送文本,服务器应简单地回显它。另一方面,当客户端发送特殊命令(例如SEND_TXT_FILE)时,服务器应接收客户端上传的文件到服务器。

我几乎把它工作了。但是,发送文件仍然存在问题。Sever不会保存整个文件,它只会创建它并断开连接。

这是协议:

CLIENT ---------- text1 ----------> SERVER
CLIENT <---------- text1 ---------- SERVER
CLIENT ---------- text2 ----------> SERVER
CLIENT <---------- text3 ---------- SERVER
CLIENT ---------- SENDTXTFILE ----------> SERVER
CLIENT <---------- OK ---------- SERVER
CLIENT ---------- FILENAME ----------> SERVER
CLIENT <---------- OK ---------- SERVER
CLIENT ---------- file content ----------> SERVER
CLIENT <--------- FILE_UPLOADED --------- SERVER
CLIENT ---------- text3 ----------> SERVER
CLIENT <---------- text3 ---------- SERVER

我该如何解决这个问题?

服务器.c

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#define BUFFER_SIZE 1024
int send_all(int sockfd, const char *buf, int len)
{
ssize_t n;
while (len > 0)
{
n = send(sockfd, buf, len, 0);
if (n < 0)
return -1;
buf += n;
len -= n;
}
return 0;
}
int recv_all(int sockfd, char *buf, int len)
{
ssize_t n;
while (len > 0)
{
n = recv(sockfd, buf, len, 0);
if (n <= 0)
return n;
buf += n;
len -= n;
}
return 1;
}
int recv_txt_file(int sockfd, int len, const char *filename)
{
FILE *fp = fopen(filename, "wb");
int total = 0, b = 0;
char buffer[BUFFER_SIZE];
memset(buffer, '', BUFFER_SIZE);
if (fp != NULL)
{
while (recv_all(sockfd, buffer, len) != 1)
{
total += b;
fwrite(buffer, 1, b, fp);
}
printf("Received byte: %dn",total);
if (b < 0)
perror("Receiving");
fclose(fp);
}
else
{
perror("File");
}
close(sockfd);
}
int main()
{
int port = 6666;
int server_fd, client_fd, read;
struct sockaddr_in server, client;
char buffer[BUFFER_SIZE], filename[BUFFER_SIZE];
char remote_ip[16];
int remote_port, res = 0;
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0)
{
perror("Could not create socket");
return 1;
}
int optval = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int));
memset(&server, '', sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(server_fd, (struct sockaddr *)&server, sizeof(server)) < 0)
{
perror("Could not bind socket");
close(server_fd);
return 1;
}
if (listen(server_fd, 1) < 0)
{
perror("Could not listen on socket");
close(server_fd);
return 1;
}
printf("Server TCP is listening on port %d ... n", port);
socklen_t client_len = sizeof(client);
client_fd = accept(server_fd, (struct sockaddr *)&client, &client_len);
if (client_fd < 0)
{
perror("Could not establish new connection");
close(server_fd);
return 1;
}
remote_port = ntohs(client.sin_port);
inet_ntop(AF_INET, &client.sin_addr, remote_ip, sizeof(remote_ip));
printf("Client IP address: %s, port %dn", remote_ip, remote_port);
while (1)
{
read = recv_all(client_fd, buffer, BUFFER_SIZE);
if (read <= 0)
{
if (read < 0)
perror("Client read failed");
else
printf("Client disconnectedn");
break;
}
if ((res = strcmp(buffer, "SENDFILE_TXTn") == 0))
{
printf("-------FROM CLIENT: %s-------n", buffer);
memset(buffer, BUFFER_SIZE, '');
strcpy(buffer, "OK");
if (send_all(client_fd, buffer, BUFFER_SIZE) < 0)
{
perror("Client write failed");
break;
}
read = recv_all(client_fd, buffer, BUFFER_SIZE);
if (read <= 0)
{
if (read < 0)
perror("Client read failed");
else
printf("Client disconnectedn");
break;
}
printf("-------FROM CLIENT: %s-------n", buffer);
memset(filename, '', BUFFER_SIZE);
strcpy(filename, buffer);
memset(buffer, BUFFER_SIZE, '');
strcpy(buffer, "OK");
if (send_all(client_fd, buffer, BUFFER_SIZE) < 0)
{
perror("Client write failed");
break;
}
recv_txt_file(client_fd, BUFFER_SIZE, filename);
}
else
{
printf("FROM CLIENT: %.*sn", BUFFER_SIZE, buffer);
if (send_all(client_fd, buffer, BUFFER_SIZE) < 0)
{
perror("Client write failed");
break;
}
}
}
close(client_fd);
close(server_fd);
return 0;
}

客户端.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#define BUFFER_SIZE 1024
socklen_t hostname_to_ip_port(char *hostname, int port, struct sockaddr_storage *addr)
{
int sockfd;
struct addrinfo hints, *servinfo;
int rv;
char service[20];
sprintf(service, "%d", port);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if ((rv = getaddrinfo(hostname, service, &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo: %sn", gai_strerror(rv));
return 0;
}
socklen_t addrlen = servinfo->ai_addrlen;
memcpy(addr, servinfo->ai_addr, addrlen);
freeaddrinfo(servinfo);
return addrlen;
}
int send_all(int sockfd, const char *buf, size_t len)
{
ssize_t n;
while (len > 0)
{
n = send(sockfd, buf, len, 0);
if (n < 0)
return -1;
buf += n;
len -= n;
}
return 0;
}
int recv_all(int sockfd, char *buf, int len)
{
ssize_t n;
while (len > 0)
{
n = recv(sockfd, buf, len, 0);
if (n <= 0)
return n;
buf += n;
len -= n;
}
return 1;
}
long int get_file_size(char filename[])
{
// opening the file in read mode
FILE *fp = fopen(filename, "r");
// checking if the file exist or not
if (fp == NULL) {
printf("File Not Found!n");
return -1;
}
fseek(fp, 0L, SEEK_END);
// calculating the size of the file
long int res = ftell(fp);
// closing the file
fclose(fp);
return res;
}
int send_txt_file(int sockfd, int len, const char *filename)
{
FILE *fp = fopen(filename, "r");
int b;
char buffer[BUFFER_SIZE];
memset(buffer, '', BUFFER_SIZE);
if (fp == NULL)
{
perror("Error while openning file");
return 0;
}
while ((b = fread(buffer, 1, BUFFER_SIZE, fp)) > 0){
send_all(sockfd, buffer, BUFFER_SIZE);
memset(buffer, '', BUFFER_SIZE);
}
fclose(fp);
return 1;
}
int main(int argc, char **argv)
{
char *hostname = "127.0.0.1";
int port = 6666;
char buffer[BUFFER_SIZE], fname[BUFFER_SIZE];
int sockfd, err, res;
struct sockaddr_storage server_addr;
socklen_t server_addr_len;
server_addr_len = hostname_to_ip_port(hostname, port, &server_addr);
if (server_addr_len == 0)
return 1;
sockfd = socket(server_addr.ss_family, SOCK_STREAM, IPPROTO_TCP);
if (sockfd < 0)
{
perror("Could not create socket");
return 1;
}
if (connect(sockfd, (struct sockaddr *)&server_addr, server_addr_len) < 0)
{
perror("Could not connect socket");
return 1;
}
while (1)
{
memset(buffer, BUFFER_SIZE, '');
memset(fname, BUFFER_SIZE, '');
printf("> ");
if (!fgets(buffer, BUFFER_SIZE, stdin))
break;
if (strstr(buffer, "SENDFILE_TXT") != NULL)
{
if (send_all(sockfd, buffer, BUFFER_SIZE) < 0)
{
perror("Could not send message");
close(sockfd);
return 1;
}
memset(buffer, BUFFER_SIZE, '');
err = recv_all(sockfd, buffer, BUFFER_SIZE);
if (err <= 0)
{
if (err < 0)
perror("Could not read message");
else
printf("Server disconnectedn");
break;
}
if ((res = strcmp(buffer, "OK") == 0))
{
printf("-------FROM SERVER: %s-------n", buffer);
printf("Give filename> ");
memset(fname, BUFFER_SIZE, '');
if (!fgets(fname, BUFFER_SIZE, stdin))
break;
if (send_all(sockfd, fname, BUFFER_SIZE) < 0)
{
perror("Could not send message");
close(sockfd);
return 1;
}
}
err = recv_all(sockfd, buffer, BUFFER_SIZE);
if (err <= 0)
{
if (err < 0)
perror("Could not read message");
else
printf("Server disconnectedn");
break;
}
fname[strlen(fname)-1] = 0;
printf("----%s----n", fname);
send_txt_file(sockfd, BUFFER_SIZE, fname);
printf("FROM SERVER: %.*sn", BUFFER_SIZE, buffer);
}
else
{
if (send_all(sockfd, buffer, BUFFER_SIZE) < 0)
{
perror("Could not send message");
close(sockfd);
return 1;
}
err = recv_all(sockfd, buffer, BUFFER_SIZE);
if (err <= 0)
{
if (err < 0)
perror("Could not read message");
else
printf("Server disconnectedn");
break;
}
printf("FROM SERVER: %.*sn", BUFFER_SIZE, buffer);
}
}
close(sockfd);
return 0;
}

使用send_txt_file()recv_txt_file()传输文件的方式不正确。


在服务器端:

当客户端连接时,服务器等待客户端为每个命令发送恰好BUFFER_SIZE(1024)个字节,不多也不少(这对于短命令来说是浪费带宽)。 收到SENDFILE_TXT命令时,服务器从客户端读取文件名(如果文件名长度正好为BUFFER_SIZE字节,这将导致缓冲区溢出),然后调用recv_txt_file()

recv_txt_file()尝试循环从客户端读取,读取正好BUFFER_SIZE块。 但是,正在使用的while循环编码不正确。它检查recv_all()的返回值是否失败,而不是成功!=检查需要改为更改为==。 而且,用于递增total并告诉fwrite()要写入多少字节的b变量永远不会设置为0 以外的任何值。它需要设置为BUFFER_SIZE,因为如果recv_all()返回 1,这就是实际读取的字节数。

但是,即使while循环编码正确,传输仍然无法正常运行,因为它要求数倍BUFFER_SIZE发送文件。 如果文件的大小不是偶数倍数,recv_all()最终将等待客户端不发送的数据,直到套接字发生错误。

此外,recv_txt_file()在传输完成后关闭连接。 它不应该这样做,因为这会阻止客户端在发送文件后发送进一步的命令。客户端在发送文件后不会关闭其连接端,因此服务器不应在收到文件后关闭其连接端。


在客户端:

当客户端发送SENDFILE_TXT命令并得到确认时,它会调用send_txt_file(),后者循环读取文件,并以BUFFER_SIZE大小的块将其发送到服务器。 如果文件大小不是BUFFER_SIZE的偶数倍,则发送的最后一个块只会浪费带宽并将随机垃圾发送到服务器。 此外,如果套接字上发生错误,您将忽略send_all()的返回值以中断循环。


客户端应在发送文件数据之前将实际文件大小发送到服务器。 然后,服务器可以先读取该大小值,以便知道何时停止读取。

话虽如此,请尝试以下更像:

服务器.c

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#include <stdint.h>
#define BUFFER_SIZE 1024
int send_all(int sockfd, const void *buf, int len)
{
ssize_t n;
const char *pbuf = (const char*) buf;
while (len > 0)
{
n = send(sockfd, pbuf, len, 0);
if (n < 0)
{
perror("Client write failed");
return n;
}
pbuf += n;
len -= n;
}
return 0;
}
int send_uint32(int sockfd, uint32_t value)
{
value = htonl(value);
if (send_all(sockfd, &value, sizeof(value)) < 0)
return -1;
return 0;
}
int send_str(int sockfd, const char *s)
{
uint32_t len = strlen(s);
int res = send_uint32(sockfd, len);
if (res == 0)
res = send_all(sockfd, s, len);
return res;
}
int recv_all(int sockfd, void * buf, int len)
{
ssize_t n;
char *pbuf = (char*) buf;
while (len > 0)
{
n = recv(sockfd, pbuf, len, 0);
if (n <= 0)
{
if (n < 0)
perror("Client read failed");
else
printf("Client disconnectedn");
return n;
}
pbuf += n;
len -= n;
}
return 1;
}
int recv_uint32(int sockfd, uint32_t *value)
{
int res = recv_all(sockfd, value, sizeof(*value));
if (res > 0)
*value = ntohl(*value);
return res;
}
int recv_uint64(int sockfd, uint64_t *value)
{
int res = recv_all(sockfd, value, sizeof(*value));
if (res > 0)
*value = ntohll(*value); // <-- use any implementation of your choosing...
return res;
}
int recv_str(int sockfd, char **str)
{
uint32_t len;
int res = recv_uint32(sockfd, &len);
if (res <= 0)
return res;
*str = (char*) malloc(len + 1);
if (*str == NULL)
{
perror("Could not allocate memory");
return -1;
}
res = recv_all(sockfd, *str, len);
if (res <= 0)
free(*str);
else
(*str)[len] = '';
return res;
}
int recv_txt_file(int sockfd)
{
char *filename;
uint64_t filesize;
if (recv_str(sockfd, &filename) <= 0)
return -1;
int res = recv_uint64(sockfd, &filesize);
if (res <= 0)
{
free(filename);
return -1;
}
printf("-------FROM CLIENT: %s-------n", filename);
FILE* fp = fopen(filename, "wb");
if (fp == NULL)
{
perror("Could not create file");
free(filename);
send_str(sockfd, "NO");
return 0;
}
free(filename);
// optional: pre-size the new file to the specified filesize...
if (send_str(sockfd, "OK") < 0)
return -1;
char buffer[BUFFER_SIZE];
int b;
uint64_t total = 0;
while (filesize > 0)
{
b = (filesize > BUFFER_SIZE) ? BUFFER_SIZE : (int) filesize;
res = recv_all(sockfd, buffer, b);
if (res <= 0)
{
fclose(fp);
return -1;
}
if (fwrite(buffer, b, 1, fp) < 1)
{
perror("Could not write to file");
fclose(fp);
send_str(sockfd, "ERROR");
return -1;
}
total += b;
filesize -= b;
}
fclose(fp);
printf("Received bytes: %lun", total);
if (send_str(sockfd, "OK") < 0)
return -1;
return 1;
}
int main()
{
int port = 6666;
int server_fd, client_fd, read;
struct sockaddr_in server, client;
char filename[BUFFER_SIZE], *cmd;
char remote_ip[16];
int remote_port, res = 0;
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0)
{
perror("Could not create socket");
return 1;
}
int optval = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int));
memset(&server, '', sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(server_fd, (struct sockaddr *) &server, sizeof(server)) < 0)
{
perror("Could not bind socket");
close(server_fd);
return 1;
}
if (listen(server_fd, 1) < 0)
{
perror("Could not listen on socket");
close(server_fd);
return 1;
}
printf("Server TCP is listening on port %d ... n", port);
socklen_t client_len = sizeof(client);
client_fd = accept(server_fd, (struct sockaddr *) &client, &client_len);
if (client_fd < 0)
{
perror("Could not establish new connection");
close(server_fd);
return 1;
}
remote_port = ntohs(client.sin_port);
inet_ntop(AF_INET, &client.sin_addr, remote_ip, sizeof(remote_ip));
printf("Client IP address: %s, port %dn", remote_ip, remote_port);
while (recv_str(client_fd, &cmd) > 0)
{
printf("-------FROM CLIENT: %s-------n", cmd);
if (strcmp(cmd, "SENDFILE_TXT") == 0)
{
if (recv_txt_file(client_fd) < 0)
break;
}
else
{
if (send_str(client_fd, cmd) < 0)
{
free(cmd);
break;
}
}
free(cmd);
}
close(client_fd);
close(server_fd);
return 0;
}

客户端.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <stdint.h>
#define BUFFER_SIZE 1024
socklen_t hostname_to_ip_port(char *hostname, int port, struct sockaddr_storage *addr)
{
int sockfd;
struct addrinfo hints, *servinfo;
int rv;
char service[20];
sprintf(service, "%d", port);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if ((rv = getaddrinfo(hostname, service, &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo: %sn", gai_strerror(rv));
return 0;
}
socklen_t addrlen = servinfo->ai_addrlen;
memcpy(addr, servinfo->ai_addr, addrlen);
freeaddrinfo(servinfo);
return addrlen;
}
int send_all(int sockfd, const void *buf, size_t len)
{
ssize_t n;
const char *pbuf = (const char *) buf;
while (len > 0)
{
n = send(sockfd, pbuf, len, 0);
if (n < 0)
{
perror("Server write failed");
return n;
}
pbuf += n;
len -= n;
}
return 0;
}
int send_uint32(int sockfd, uint32_t value)
{
value = htonl(value);
return send_all(sockfd, &value, sizeof(value));
}
int send_uint64(int sockfd, uint64_t value)
{
value = htonll(value); // <-- use any implementation of your choosing...
return send_all(sockfd, &value, sizeof(value));
}
int send_str(int sockfd, const char *s)
{
uint32_t len = strlen(s);
int res = send_uint32(sockfd, len);
if (res == 0)
res = send_all(sockfd, s, len);
return res;
}
int recv_all(int sockfd, void *buf, int len)
{
ssize_t n;
char *pbuf = (char*) buf;
while (len > 0)
{
n = recv(sockfd, pbuf, len, 0);
if (n <= 0)
{
if (n < 0)
perror("Server read failed");
else
printf("Server disconnectedn");
return n;
}
pbuf += n;
len -= n;
}
return 1;
}
int recv_uint32(int sockfd, uint32_t *value)
{
int res = recv_all(sockfd, value, sizeof(*value));
if (res > 0)
*value = ntohl(*value);
return res;
}
int recv_str(int sockfd, char **str)
{
uint32_t len;
int res = recv_uint32(sockfd, &len);
if (res <= 0)
return res;
*str = (char*) malloc(len + 1);
if (*str == NULL)
{
perror("Could not allocate memory");
return -1;
}
res = recv_all(sockfd, *str, len);
if (res <= 0)
free(*str);
else
(*str)[len] = '';
return res;
}
int send_txt_file(int sockfd, const char *filename)
{
char *resp;
int res;
long int filesize;
char buffer[BUFFER_SIZE];
int b;
FILE* fp = fopen(filename, "rb");
if (fp == NULL)
{
printf("Could not open file!n");
return 0;
}
fseek(fp, 0L, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
if (filesize < 0)
{
fclose(fp);
return 0;
}
if (send_str(sockfd, "SENDFILE_TXT") < 0)
{
fclose(fp);
return -1;
}
if (send_str(sockfd, filename) < 0)
{
fclose(fp);
return -1;
}
if (send_uint64(sockfd, filesize) < 0)
{
fclose(fp);
return -1;
}
res = recv_str(sockfd, &resp);
if (res <= 0)
return -1;
printf("-------FROM SERVER: %s-------n", resp);
if (strcmp(resp, "OK") != 0)
{
free(resp);
fclose(fp);
return 0;
}
free(resp);
while (filesize > 0)
{
b = (filesize > BUFFER_SIZE) ? BUFFER_SIZE : (int) filesize;
b = fread(buffer, 1, b, fp);
if (b < 1)
{
fclose(fp);
return -1;
}
if (send_all(sockfd, buffer, b) < 0)
{
fclose(fp);
return -1;
}
filesize -= b;
}
fclose(fp);
res = recv_str(sockfd, &resp);
if (res <= 0)
return -1;
printf("-------FROM SERVER: %s-------n", resp);
free(resp);
return 0;
}
int prompt(const char *text, char **input)
{
*input = NULL;
size_t size = 0;
printf("%s> ", text);
ssize_t len = getline(input, &size, stdin);
if (len < 0)
return len;
if ((*input)[len-1] == 'n')
{
--len;
(*input)[len] = '';
}
return len;
}
int main()
{
char *hostname = "127.0.0.1";
int port = 6666;
char *cmd, *resp, *fname;
size_t size;
ssize_t len;
int sockfd, res;
struct sockaddr_storage server_addr;
socklen_t server_addr_len;
server_addr_len = hostname_to_ip_port(hostname, port, &server_addr);
if (server_addr_len == 0)
return 1;
sockfd = socket(server_addr.ss_family, SOCK_STREAM, IPPROTO_TCP);
if (sockfd < 0)
{
perror("Could not create socket");
return 1;
}
if (connect(sockfd, (struct sockaddr *) &server_addr, server_addr_len) < 0)
{
perror("Could not connect socket");
return 1;
}
while (prompt("", &cmd) >= 0)
{
if (strcmp(cmd, "SENDFILE_TXT") == 0)
{
if (prompt("Give filename", &fname) < 0)
break;
if (send_txt_file(sockfd, fname) < 0)
break;
free(fname);
}
else
{
if (send_str(sockfd, cmd) < 0)
{
free(cmd);
close(sockfd);
return 1;
}
if (recv_str(sockfd, &resp) <= 0)
break;
printf("FROM SERVER: %sn", resp);
free(resp);
}
free(cmd);
}
close(sockfd);
return 0;
}

关于:

int total = 0, b = 0;

while(recv_all(sockfd, buffer, len) != 1)
{
total += b;
fwrite(buffer, 1, b, fp);

totalb永远不会从其初始值 0 移动。 因此,将 0 字节写入输出文件。

相关内容

  • 没有找到相关文章

最新更新