TCP / IP 소켓 (웹 서버)을 통해 파일 보내기

조던 데이비스

웹 서버의 베어 본을 작성하고 있지만 내 파일이 내 소켓을 통해 전송되지 않는 이유를 파악할 수 없습니다. 파일에 연결하지 않고 모든 send()파일을 처리 하지 않습니다. 잃어버린?

// CODE (server.c)

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

int main(void) {    
   int create_socket, new_socket;    
   socklen_t addrlen;    
   int bufsize = 1024;    
   char *buffer = malloc(bufsize);    
   struct sockaddr_in address;    

   if ((create_socket = socket(AF_INET, SOCK_STREAM, 0)) > 0){    
      printf("The socket was created\n");
   }

   address.sin_family = AF_INET;    
   address.sin_addr.s_addr = INADDR_ANY;    
   address.sin_port = htons(80);    

   if (bind(create_socket, (struct sockaddr *) &address, sizeof(address)) == 0){    
      printf("Binding Socket\n");
   }

    long fsize;
    FILE *fp = fopen("index.html", "r");
    fseek(fp, 0, SEEK_END);
    fsize = ftell(fp);
    rewind(fp);
    char *msg = malloc(fsize + 1);
    fread(msg, sizeof(msg), 1, fp);

   while (1) {    
      if (listen(create_socket, 10) < 0) {    
         perror("server: listen");    
         exit(1);    
      }    

      if ((new_socket = accept(create_socket, (struct sockaddr *) &address, &addrlen)) < 0) {    
         perror("server: accept");    
         exit(1);    
      }    

      if (new_socket > 0){    
         printf("The Client is connected...\n");
      }

        recv(new_socket, buffer, bufsize, 0);    
        printf("%s\n", buffer);    
        write(new_socket, "HTTP/1.1 200 OK\n", 16);
        write(new_socket, "Content-length: 46\n", 19);
        write(new_socket, "Content-Type: text/html\n\n", 25);
/*      write(new_socket, "<html><body><H1>Hello world</H1></body></html>",46); */
        if((send(new_socket, msg, fsize+1, 0)) > 0){
            printf("success");
        }     
        else{
            printf("failed");
        }
      close(new_socket);    
   }    
   close(create_socket);    
   return 0;    
}

// FILE (index.html) * 동일한 디렉토리

<html>
<body>
    <h1>Hello World</h1>
</body>
</html>
레미 르보

코드는 여러 가지 이유로 완전히 깨졌습니다. 대신 다음과 같이 시도하십시오.

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

bool writeDataToClient(int sckt, const void *data, int datalen)
{
    const char *pdata = (const char*) data;

    while (datalen > 0){
        int numSent = send(sckt, pdata, datalen, 0);
        if (numSent <= 0){
            if (numSent == 0){
                printf("The client was not written to: disconnected\n");
            } else {
                perror("The client was not written to");
            }
            return false;
        }
        pdata += numSent;
        datalen -= numSent;
    }

    return true;
}

bool writeStrToClient(int sckt, const char *str)
{
    return writeDataToClient(sckt, str, strlen(str));
}

int main(void){
    int create_socket, new_socket;    
    char *buffer;
    int bufsize = 1024;    
    struct sockaddr_in address;    
    socklen_t addrlen;    

    buffer = (char*) malloc(bufsize);    
    if (!buffer){
        printf("The receive buffer was not allocated\n");
        exit(1);    
    }

    create_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (create_socket == -1){    
        perror("The socket was not created");    
        exit(1);    
    }

    printf("The socket was created\n");

    memset(&address, 0, sizeof(address));    
    address.sin_family = AF_INET;    
    address.sin_addr.s_addr = INADDR_ANY;    
    address.sin_port = htons(80);    

    if (bind(create_socket, (struct sockaddr *) &address, sizeof(address)) == -1){    
        perror("The socket was not bound");    
        exit(1);    
    }

    printf("The socket is bound\n");    

    long fsize;
    FILE *fp = fopen("index.html", "rb");
    if (!fp){
        perror("The file was not opened");    
        exit(1);    
    }

    printf("The file was opened\n");

    if (fseek(fp, 0, SEEK_END) == -1){
        perror("The file was not seeked");
        exit(1);
    }

    fsize = ftell(fp);
    if (fsize == -1) {
        perror("The file size was not retrieved");
        exit(1);
    }
    rewind(fp);

    char *msg = (char*) malloc(fsize);
    if (!msg){
        perror("The file buffer was not allocated\n");
        exit(1);
    }

    if (fread(msg, fsize, 1, fp) != 1){
        perror("The file was not read\n");
        exit(1);
    }
    fclose(fp);

    printf("The file size is %ld\n", fsize);

    if (listen(create_socket, 10) == -1){
        perror("The socket was not opened for listening");    
        exit(1);    
    }    

    printf("The socket is listening\n");

    while (1) {    

        addrlen = sizeof(address);
        new_socket = accept(create_socket, (struct sockaddr *) &address, &addrlen);

        if (new_socket == -1) {    
            perror("A client was not accepted");    
            exit(1);    
        }    

        printf("A client is connected from %s:%hu...\n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));    

        // I will leave it as an exercise for you to implement
        // a proper HTTP request parser here...
        int numRead = recv(new_socket, buffer, bufsize, 0);
        if (numRead < 1){
            if (numRead == 0){
                printf("The client was not read from: disconnected\n");
            } else {
                perror("The client was not read from");
            }
            close(new_socket);
            continue;
        }
        printf("%.*s\n", numRead, buffer);    

        if (!writeStrToClient(new_socket, "HTTP/1.1 200 OK\r\n")){
            close(new_socket);
            continue;
        }

        char clen[40];
        sprintf(clen, "Content-length: %ld\r\n", fsize);
        if (!writeStrToClient(new_socket, clen)){
            close(new_socket);
            continue;
        }

        if (!writeStrToClient(new_socket, "Content-Type: text/html\r\n")){
            close(new_socket);
            continue;
        }

        if (!writeStrToClient(new_socket, "Connection: close\r\n\r\n") == -1){
            close(new_socket);
            continue;
        }

        //if (!writeStrToClient(new_socket, "<html><body><H1>Hello world</H1></body></html>")){
        if (!writeDataToClient(new_socket, msg, fsize)){
            close(new_socket);
            continue;
        }

        printf("The file was sent successfully\n");
        close(new_socket);    
   }    

   close(create_socket);    
   return 0;    
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

파이썬에서 TCP 소켓을 통해 파일 보내기

TCP 소켓을 통해 파일 보내기 C++ | 창

TCP 소켓을 통해 여러 파일 보내기

파이썬에서 TCP 소켓을 통해 클라이언트-서버 간 파일 보내기?

TCP 소켓 파이썬을 통해 단일 바이트 보내기

Socket.io 웹 소켓을 통해 내 앱에서 json 및 오디오 파일을 특정 socketId로 보내기

소켓을 통해 파일 보내기-버퍼 크기

불완전한 TCP 소켓을 통해 char 버퍼 보내기

파이썬 3에서 소켓을 통해 파일 보내기

C에서 tcp 소켓을 통해 HTTP를 통해 파일을 어떻게 보내나요?

Python에서 TCP 소켓을 통해 목록 보내기

C의 소켓을 사용하여 TCP를 통해 오디오 파일 보내기

소켓을 통해 PC에서 Android로 파일 보내기

TCP / IP 소켓을 통해 PC에서 라즈베리 파이로

TCP 소켓을 통해 큰 Base64 문자열 보내기

c의 tcp 소켓을 통해 구조체 보내기

TCP 소켓을 통해 16진수 변수 보내기

phoenix 채널을 통해 웹 소켓을 통해 파일을 보내는 방법이 있습니까?

Java 소켓을 통해 여러 파일 보내기

소켓을 통해 큰 파일 보내기

소켓을 통해 대용량 JSON 파일 보내기

소켓을 통해 Jar 파일 보내기

소켓을 통해 웹캠 피드 보내기

웹 소켓을 통해 popen 출력 보내기

웹 소켓을 통해 RabbitMQ 메시지 보내기

웹 소켓을 통해 STOMP 프레임 보내기

TCP 소켓을 통해 서버에 오디오 쓰기

Dart에서 소켓을 통해 파일을 보내는 방법

C #에서 소켓을 통해 파일을 보내는 방법

TOP 리스트

  1. 1

    셀레늄의 모델 대화 상자에서 텍스트를 추출하는 방법은 무엇입니까?

  2. 2

    Blazor 0.9.0 및 ASP.NET Core 3 미리보기 4를 사용한 JWT 인증

  3. 3

    openCV python을 사용하여 텍스트 문서에서 워터 마크를 제거하는 방법은 무엇입니까?

  4. 4

    C # 16 진수 값 0x12는 잘못된 문자입니다.

  5. 5

    Excel : 합계가 N보다 크거나 같은 상위 값 찾기

  6. 6

    오류 : MSB4803 : MSBuild의 .NET Core 버전에서 "ResolveComReference"작업이 지원되지 않습니다.

  7. 7

    R에서 Excel로 내보낼 때 CET / CEST 시간 이동이 삭제됨

  8. 8

    node.js + postgres : "$ 1"또는 그 근처에서 구문 오류

  9. 9

    확대 후 하이 차트에서 Y 축이 잘못 정렬 됨

  10. 10

    EPPlus에서 행 높이를 설정할 때 이상한 동작

  11. 11

    Ionic 2 로더가 적시에 표시되지 않음

  12. 12

    MS Access 부분 일치 2 테이블

  13. 13

    EPPlus에서 병합 된 셀의 행 높이 자동 맞춤

  14. 14

    ExecuteNonQuery- 연결 속성이 초기화되지 않았습니다.

  15. 15

    ResponseEntity를 사용하고 InputStream이 닫히는 지 확인하는 적절한 스트리밍 방법

  16. 16

    PrematureCloseException : 연결이 너무 일찍 닫혔습니다.

  17. 17

    오류 : "const wchar_t *"유형의 인수가 "WCHAR *"유형의 매개 변수와 호환되지 않습니다.

  18. 18

    Java에서 이미지를 2 색으로 변환

  19. 19

    overflow-y를 사용할 때 스크롤 버벅 거림 줄이기 : scroll;

  20. 20

    Java에서 Apache POI를 사용하여 테이블 크기 및 간격을 단어로 설정하는 방법

  21. 21

    Android Kotlin은 다른 활동에서 함수를 호출합니다.

뜨겁다태그

보관