C++Builder Programming Forum
C++Builder  |  Delphi  |  FireMonkey  |  C/C++  |  Free Pascal  |  Firebird
볼랜드포럼 BorlandForum
 경고! 게시물 작성자의 사전 허락없는 메일주소 추출행위 절대 금지
C++빌더 포럼
Q & A
FAQ
팁&트릭
강좌/문서
자료실
컴포넌트/라이브러리
메신저 프로젝트
볼랜드포럼 홈
헤드라인 뉴스
IT 뉴스
공지사항
자유게시판
해피 브레이크
공동 프로젝트
구인/구직
회원 장터
건의사항
운영진 게시판
회원 메뉴
북마크
볼랜드포럼 광고 모집

C++빌더 Q&A
C++Builder Programming Q&A
[72718] c++ TCP 클라이언트 부분 에러 질문드려도될까요
forCPP [kks4825] 4287 읽음    2015-06-05 12:30



#include "myp2p.h"


int _seq_num = 0;


void error_quit(char * err_str)
{
    printf("%s \n", err_str);
    exit(1);
}


int send_nbytes(SOCKET fd, const void* vptr, size_t n)
{
    int      nleft;
    int     nwritten;
    const char* ptr;

    ptr = (const char*)vptr;
    nleft = n;
    while (nleft > 0) {
        if ((nwritten = send(fd, ptr, nleft, 0)) <= 0)
        {
            return(-1);
        }
        nleft -= nwritten;
        ptr += nwritten;
    }
    return(n);
}


int make_a_packet(void * pkt, char * data, int data_size)
{
    unsigned int seq_num = _seq_num++; //test data
    unsigned short packet_type = 2; //test data
    unsigned short data_len = data_size;

    struct common_pkt_header cmn_pkt_hdr;

    cmn_pkt_hdr.seq_num = htonl(seq_num);
    cmn_pkt_hdr.packet_type = htons(packet_type);
    cmn_pkt_hdr.data_len = htons(data_size);

    int hdr_len = sizeof(struct common_pkt_header);

    memcpy(pkt, (const void*)&cmn_pkt_hdr, hdr_len);

    memcpy((void *)((char *)pkt + hdr_len), data, data_size);

    return hdr_len + data_size;

}




int main(int argc, char **argv)
{
    SOCKET sockfd;
    WSADATA wsaData;
    struct sockaddr_in addr;

    char buf[MAX_PACKETLEN];
    char rbuf[MAX_PACKETLEN];
    char pkt[MAX_PACKETLEN];

    int byteSent = 0;
    int byteRcvd = 0;

    if (argc != 2)
    {
        printf("Usage : %s [ip address]\n", argv[0]);
        return 1;
    }

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR)
    {
        printf("WSAStartup error\n");
        return 1;
    }

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
    {
        printf("Socket creation error error\n");
        WSACleanup();
        return 1;
    }
    memset((void *)&addr, 0x00, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    addr.sin_port = htons(PORT_NUM);

    if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
    {
        printf("Connect error\n");
        WSACleanup();
        return 1;
    }

    int  maxfdp1;        /* max file desciptor plus 1 */
    fd_set read_set;     /* set of fd's to read from  */

    struct timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = 1000;

    printf("> ");

    while (1)
    {

        FD_ZERO(&read_set);            /* make sure no other fd are set */
        //FD_SET(fileno(stdin), &read_set); // This line does not work in Windows !!
        FD_SET(sockfd, &read_set);
        //maxfdp1 = max(fileno(stdin), sockfd) + 1; // This line does not work in Windows !!
        maxfdp1 = sockfd + 1;

        int s_ret = 0;
        if ((s_ret = select(maxfdp1, &read_set, NULL, NULL, &tv)) < 0)
        {
            printf("select error");
            exit(1);
        }
        if (s_ret == 0) // select timeout occurs
        {
            if (_kbhit()) // check if there are avilable keyboard inputs in buffer
            {
                printf("> ");
                if (fgets(buf, MAX_PACKETLEN, stdin) == NULL)
                    break;
                if (strncmp(buf, "quit\n", 5) == 0)
                {
                    break;
                }

                int pkt_len = make_a_packet(pkt, buf, strlen(buf));

                byteSent = send_nbytes(sockfd, pkt, pkt_len);

                printf("pkt_len: %d, byteSent: %d \n", pkt_len, byteSent);

                if (byteSent <= 0)
                {
                    error_quit("Error in sending OR connection has been closed");
                }
            }
        }


        if (FD_ISSET(sockfd, &read_set))
        {  /* the socket has data */
            memset(rbuf, 0x00, MAX_PACKETLEN);
            byteRcvd = recv(sockfd, (char *)rbuf, MAX_PACKETLEN, 0);
            if (byteRcvd < 0)
            {
                error_quit("error reading a line from the tcp socket");
            }
            else if (byteRcvd == 0)
            {
                error_quit("server quits on me");
            }

            printf("Server echoed > ");
            fputs(rbuf, stdout);
        }


    }
    closesocket(sockfd);
    WSACleanup();
    return 0;
}

위에가 서버와 패킷전송을 주고받는 클라이언트 부분 소스입니다.

그런데 이 소스코드를 빌드하고 디버깅을 실행하면 아래와 같은 에러 메시지(?)가 발생하면서

콘솔창이 떴다가 바로 사라집니다..

'p2p_client.exe'(Win32): 'C:\Users\311-3\Documents\Visu
<
<
<
al Studio 2013\Projects\p2p_client\Debug\p2p_client.exe'을(를) 로드했습니다. 기호가 로드되었습니다.

'p2p_client.exe'(Win32): 'C:\Windows\System32\ntdll.dll'을(를) 로드했습니다. 기호가 로드되었습니다.
'p2p_client.exe'(Win32): 'C:\Windows\System32\kernel32.dll'을(를) 로드했습니다. 기호가 로드되었습니다.
'p2p_client.exe'(Win32): 'C:\Windows\System32\KernelBase.dll'을(를) 로드했습니다. 기호가 로드되었습니다.
'p2p_client.exe'(Win32): 'C:\Windows\System32\ws2_32.dll'을(를) 로드했습니다. 기호가 로드되었습니다.
'p2p_client.exe'(Win32): 'C:\Windows\System32\msvcrt.dll'을(를) 로드했습니다. 기호가 로드되었습니다.
'p2p_client.exe'(Win32): 'C:\Windows\System32\rpcrt4.dll'을(를) 로드했습니다. 기호가 로드되었습니다.
'p2p_client.exe'(Win32): 'C:\Windows\System32\nsi.dll'을(를) 로드했습니다. 기호가 로드되었습니다.
'p2p_client.exe'(Win32): 'C:\Windows\System32\msvcr120d.dll'을(를) 로드했습니다. 기호가 로드되었습니다.
'[1672] p2p_client.exe' 프로그램이 종료되었습니다(코드: 1 (0x1)).

구글링하고 찾아봐서 기호 로드하는 법 까지는 찾아왔는데 여기서 문제가 되네요..

콘솔창 안꺼지게 하려고 getchar()이나 system("pause") 같은 함수를 쓰면

입력값 받고 바로 꺼지니 답답하네요....

해결책 알고계신분 부탁드리겠습니다

+ -

관련 글 리스트
72718 c++ TCP 클라이언트 부분 에러 질문드려도될까요 forCPP 4287 2015/06/05
Google
Copyright © 1999-2015, borlandforum.com. All right reserved.