C++程式碼實現一個簡易http服務端,返回給客戶端一張圖片

Eaven_Wang發表於2024-06-03

注意事項

  • 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;
}

相關文章