如何使用套接字 C/C++ 以块形式发送文件
how to send files in chunk using socket c/C++?
我一直在尝试找到如何在 C 或 C++ 中以块的形式发送文件我看了这里的一些例子,没有找到好的例子。我对 C/C++ 中的 Sockect 编程非常陌生
http://beej.us/guide/bgnet/html/single/bgnet.html
任何想法我需要如何在客户端和服务器之间以块形式发送文件? 客户端请求文件,服务器将其发送回去。
我找到了这个发送,但不确定是否接收它。
#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 socketn");
int connectionSocket = connect(sockFd, (struct sockaddr *) &server, sizeof(struct sockaddr) );
if(connectionSocket < 0)
perror("connection not establishedn");
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 %dn", bytesRead);
printf("receivnig datan");
bytesSent = write(fd, buffer, bytesRead);
printf("bytes written %dn", bytesSent);
if(bytesSent < 0)
perror("Failed to send a message");
}
close(fd);
close(sockFd);
return 0;
}
希望这有帮助
看看TCP_CORK(男人 7 tcp)。但实际上,除了你想成为套接字/网络编程专家,使用库!想想你的下一个问题:数据加密(例如HTTPS/SSL)。图书馆关心血腥的细节...
相关文章:
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- 从套接字 C++ 发送和接收文件
- 如何从 boost::asio::ssl::stream<boost::asio::ip::tcp::socket> 获取本机套接字文件描述器?
- 如何在不设置 ulimit -n 的情况下解决套接字程序打开太多文件的错误
- 从 PHP 调用已编译的C++可执行文件来创建套接字
- 无法从零MQ ZMQ_SERVER套接字中获取文件描述符
- read() 上的不同行为取决于写入不可写内存时表示文件、匿名管道或套接字的文件描述符
- 在通过套接字向服务器发送文件数据时,我得到了一些垃圾值?为什么
- 带有线程的 Linux 套接字文件描述符
- Python和C++之间使用本地文件套接字的进程间通信
- 套接字请求不返回整个文件
- 通过网络中的套接字进行文件传输时,该程序中的文件传输错误是什么
- 套接字编程:"接受:错误的文件描述符"
- 提升 ASIO 套接字使用文件描述符
- 通过套接字发送二进制文件.文本文件有效,其他文件无效
- 从套接字接收到二进制数据后,使用c++将二进制数据写入文件
- Unix 域套接字:发送文件描述符和 select()
- 更改 Linux 套接字文件权限
- 使用SFML TCP套接字和数据包破坏文件