gpt4 book ai didi

c - 如何使用C编程将文本文件从服务器发送到客户端

转载 作者:行者123 更新时间:2023-12-05 01:27:22 25 4
gpt4 key购买 nike

我正在尝试将文本文件从服务器发送到客户端,但不确定如何继续进行编码。

我一直在阅读一些教程并设法从客户端接收数据,然后向客户端发送确认消息,表示已收到数据。但我想修改它,以便我将整个文本文件发送给客户端。

我是 C 和 TCP 套接字编程的新手,所以任何见解都将不胜感激。

到目前为止,我的服务器代码:

/* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

void error(const char *msg) {
perror(msg);
exit(1);
}

int main(int argc, char *argv[]) {

int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr, "ERROR, no port provided\n");
exit(1);
}
// Create a TCP socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof (serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
// Assign a name/port number to socket
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof (serv_addr)) < 0)
error("ERROR on binding");
// Establish a queue for connections
listen(sockfd, 5);
clilen = sizeof (cli_addr);
// Extract a connection from the queue
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer, 256);
// Read/write
n = read(newsockfd, buffer, 255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n", buffer);
n = write(newsockfd, "I got your message", 18);
if (n < 0) error("ERROR writing to socket");
close(newsockfd);
close(sockfd);
return 0;
}

最佳答案

用一个

while ((nread = read(filefd, filebuf, sizeof(filebuf))) > 0) {
size_t toread = nread, off = 0, wr;
while (toread > 0) {
wr = write(connfd, filebuf + off, toread);
if (wr >= 0) {
toread -= wr;
off += wr;
} else {
/* handle a write error */
}
}
}

环形。

关于c - 如何使用C编程将文本文件从服务器发送到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8284451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com