注意事项
- sprintf读取字符串时,遇到\0会结束,所以不能用sprintf来读取* pictureBuffer
- void *memcpy(void *str1, const void *str2, size_t n),str2会覆盖str1里的内容
代码
#include <func.h>
char pictureBuffer[150 * 1024];
char buffer[200 * 1024];
int main()
{
int sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd == -1){
perror("socket");
}
int fd = open("./dog.jpg",O_RDONLY);
if(fd == -1){
perror("open");
}
struct stat st;
if (fstat(fd, &st) == -1) {
perror("fstat");
close(fd);
close(sfd);
exit(EXIT_FAILURE);
}
size_t fileSize = st.st_size;
memset(pictureBuffer,0,sizeof(pictureBuffer));
int ret = read(fd,pictureBuffer,fileSize);
struct sockaddr_in serverAddr;
serverAddr.sin_addr.s_addr = inet_addr("192.168.44.128");
serverAddr.sin_port = htons(8081);
serverAddr.sin_family = AF_INET;
int on = 1;
ret = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
ret = bind(sfd,(struct sockaddr*)&serverAddr,sizeof(serverAddr));
if(ret == -1){
perror("bind");
}
ret = listen(sfd,10);
if(ret == -1){
perror("listen");
}
while(1){
struct sockaddr_in clientAddr;
memset(&clientAddr,0,sizeof(clientAddr));
socklen_t len = sizeof(clientAddr);
int clientfd = accept(sfd,(struct sockaddr*)&clientAddr,&len);
if(clientfd == -1){
perror("accept");
}
const char* startLine = "HTTP/1.1 200 OK\r\n";
const char* headers = "Server: HiaServer\r\n"
"Content-Type: image/jpeg\r\n"
"Content-Length: ";
const char* emptyLine = "\r\n";
sprintf(buffer,"%s%s%ld\r\n%s",
startLine,headers,fileSize,emptyLine);
ret = send(clientfd,buffer,strlen(buffer),0);
send(clientfd,pictureBuffer,fileSize,0);
printf("\nsend %ld bytes\n",fileSize + strlen(buffer));
close(clientfd);
}
close(fd);
close(sfd);
return 0;
}
标签:http,int,pictureBuffer,C++,ret,serverAddr,perror,sfd,服务端
From: https://www.cnblogs.com/EavenWang/p/18229729