gpt4 book ai didi

c++ - 如何使用套接字 c/C++ 以 block 的形式发送文件?

转载 作者:太空狗 更新时间:2023-10-29 23:05:31 24 4
gpt4 key购买 nike

我一直在尝试寻找如何在 C 或 C++ 中以 block 的形式发送文件我在这里查看了一些示例,但没有找到很好的示例。我对 C/C++ 中的 sockect 编程很陌生

http://beej.us/guide/bgnet/html/single/bgnet.html

我需要如何在客户端和服务器之间以 block 的形式发送文件?客户端请求文件,服务器发回。

我发现这个要发送,但不确定是否收到。

#include <sys/types.h>
#include <sys/socket.h>

int sendall(int s, char *buf, int *len)
{
int total = 0; // how many bytes we've sent
int bytesleft = *len; // how many we have left to send
int n;

while(total < *len) {
n = send(s, buf+total, bytesleft, 0);
if (n == -1) { break; }
total += n;
bytesleft -= n;
}

*len = total; // return number actually sent here

return n==-1?-1:0; // return -1 on failure, 0 on success
}

最佳答案

我刚刚编写了这段代码,用于在 Client using linux sockets in C 中接收文件。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>


#define PORT 4118

#define MaxBufferLength 1024 // set the size of data you want to recieve from Server


int main()
{
int sockFd, bytesRead= 1, bytesSent;

char buffer[MaxBufferLength];

struct sockaddr_in server, client;


server.sin_port= htons(PORT);
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");

sockFd = socket(AF_INET, SOCK_STREAM, 0);


if(sockFd < 0)
printf("Unable to open socket\n");

int connectionSocket = connect(sockFd, (struct sockaddr *) &server, sizeof(struct sockaddr) );

if(connectionSocket < 0)
perror("connection not established\n");


int fd = open("helloworlds.txt",O_CREAT | O_WRONLY,S_IRUSR | S_IWUSR);

if(fd == -1)
perror("couldn't openf iel");

while(bytesRead > 0)
{

bytesRead = recv(sockFd, buffer, MaxBufferLength, 0);

if(bytesRead == 0)
{

break;
}

printf("bytes read %d\n", bytesRead);

printf("receivnig data\n");

bytesSent = write(fd, buffer, bytesRead);


printf("bytes written %d\n", bytesSent);

if(bytesSent < 0)
perror("Failed to send a message");

}


close(fd);

close(sockFd);

return 0;

}

希望对你有帮助

关于c++ - 如何使用套接字 c/C++ 以 block 的形式发送文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19017651/

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