[re] 소켓

조회 수 5839 추천 수 123 2002.10.19 22:46:28
hongiro *.243.40.166
#include <winsock2.h>
#include <windows.h>
#include "resource.h"
#include "ya.h"

////////////////////////////////////////////////////////////////////////////////////////////////////

#define WM_CLIENTMSG   (WM_USER + 1)

////////////////////////////////////////////////////////////////////////////////////////////////////

BOOL StartWinsock() ;
BOOL CreateSocket(SOCKET *s) ;
void EndWinsock() ;
BOOL Select( HWND hwnd, SOCKET s, int Msg, int flag ) ;
BOOL Connect( char *pAddr, short port) ;
BOOL RecvMsg( SOCKET ClientSocket, char *recvbuff, HWND hwnd ) ;
BOOL SendMsg( SOCKET ClientSocket, char *sendbuff, int size) ;

////////////////////////////////////////////////////////////////////////////////////////////////////

SOCKET g_socket ;
char g_Buff[100] ;

char g_recvbuf[256] ;
int   g_bufsize ;

////////////////////////////////////////////////////////////////////////////////////////////////////


BOOL CALLBACK DlgProc(HWND hwnd, UINT iMsg, WPARAM wparam, LPARAM lparam) ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
        int ret ;
        
        if(!StartWinsock())
        {
                AfxMessageBox("StartWinsock() Error") ;
                return 0 ;
        }

        ret = DialogBox(hInstance, MAKEINTRESOURCE( IDD_DIALOG1 ), NULL, ( DLGPROC )DlgProc );
        if(ret != 0)
        {
                AfxMessageBox("StartWinsock() Error") ;
                EndWinsock() ;
                return 0 ;
        }

        EndWinsock() ;

        return 0 ;
}

BOOL CALLBACK DlgProc(HWND hwnd, UINT iMsg, WPARAM wparam, LPARAM lparam)
{
        char IPAddress[50] = {0,} ;
        HWND hListWnd ;
        short port ;

        switch(iMsg)
        {
        case WM_INITDIALOG :

                CreateSocket(&g_socket) ;
                Select(hwnd, g_socket, WM_CLIENTMSG, FD_CONNECT) ;
                SetWindowText(hwnd, "client") ;
                CenterWindow(hwnd) ;

                return TRUE ;
        case WM_COMMAND :

                switch(LOWORD(wparam))
                {
                case IDC_CONNECT :

                        if(g_socket == INVALID_SOCKET)
                        {
                                CreateSocket(&g_socket) ;
                                Select(hwnd, g_socket, WM_CLIENTMSG, FD_CONNECT | FD_READ) ;
                        }

                        GetDlgItemText( hwnd, IDC_ADDRESS, IPAddress, sizeof(IPAddress) );
                        port = GetDlgItemInt(hwnd, IDC_PORT, NULL, TRUE) ;
                        if( Connect( IPAddress, port ) )
                        {                                  
                                  if( WSAEWOULDBLOCK == WSAGetLastError() )
                                {
                                        hListWnd = GetDlgItem( hwnd, IDC_RECVLIST );
                                        SendLogMessage( hListWnd, "Server 접속이 대기중입니다..." );                                                          
                                }
                                else
                                {
                                        hListWnd = GetDlgItem( hwnd, IDC_RECVLIST );
                                        SendLogMessage( hListWnd, "Server 접속이 성공적입니다..." );                                                          
                                }
                        }
                        else
                        {
                                hListWnd = GetDlgItem( hwnd, IDC_RECVLIST );
                                SendLogMessage( hListWnd, "Server 접속에 실패 했습니다..." );                                                          
                        }        
                        return TRUE ;
                case IDC_DISCONNECT :

                        closesocket(g_socket) ;
                        g_socket = INVALID_SOCKET ;

                        return TRUE ;
                case IDC_SEND :

                        ZeroMemory( g_Buff, sizeof(g_Buff) );

                        if( GetDlgItemText( hwnd, IDC_MSGEDIT, g_Buff, sizeof(g_Buff) ) > 0 )
                        {                
                                SetDlgItemText(hwnd, IDC_MSGEDIT, "") ;
                                SendMsg( g_socket, g_Buff, strlen(g_Buff));
                        }

                        break ;
                case IDCANCEL :

                        EndDialog(hwnd, FALSE) ;

                        return TRUE ;
                }
                return TRUE ;
        case WM_CLIENTMSG :                
          
                switch( WSAGETSELECTEVENT(lparam) )
                {
                case FD_CONNECT :                  
                
                        Select( hwnd, g_socket, WM_CLIENTMSG, FD_READ | FD_CLOSE );
                        hListWnd = GetDlgItem( hwnd, IDC_RECVLIST );
                                        
                        return TRUE ;
                case FD_READ :  

                        hListWnd = GetDlgItem( hwnd, IDC_RECVLIST );
                         RecvMsg( wparam, g_recvbuf, hListWnd );
                        SendLogMessage( hListWnd, "%s", g_recvbuf );

                        return TRUE ;
                case FD_CLOSE :

                        hListWnd = GetDlgItem( hwnd, IDC_RECVLIST );
                        SendLogMessage( hListWnd, "%s", "Server 가 종료 되었습니다"  );
                        closesocket(g_socket) ;
                        g_socket = INVALID_SOCKET ;

                        return TRUE ;                                                
                }
                return TRUE;
        }
        return FALSE ;
}

BOOL StartWinsock( )
{
     WSADATA wsd;
     int ret;
    
     //소켓 라이브러리 초기화
     ret = WSAStartup( MAKEWORD(2,2), &wsd );
     if( ret == SOCKET_ERROR )
     {
          AfxMessageBox( "StartWinSock() -> WSAStartup( ) 함수 실패... " );
          return FALSE;
     }
    
     return TRUE;
}

BOOL CreateSocket(SOCKET *s)
{
        *s = socket( AF_INET, SOCK_STREAM, 0 );
    if( g_socket == INVALID_SOCKET )
    {
         AfxMessageBox( "StartWinSock() -> socket( ) 함수 실패... " );
         return FALSE;
    }    
    
    return TRUE;
}


void EndWinsock( )
{
    if( g_socket )
        closesocket( g_socket );
    
    WSACleanup( );
}

BOOL Select( HWND hwnd, SOCKET s, int Msg, int flag )
{
        int  ret;

        ret = WSAAsyncSelect( s, hwnd, Msg, flag );
        if( ret == SOCKET_ERROR )
        {
          AfxMessageBox( "Select() -> WSAAsyncSelect( ) 함수 실패... " );
          return FALSE;
        }

        return TRUE;
}

BOOL Connect( char *pAddr, short port )
{
        struct hostent*    host;
    struct sockaddr_in sa;
        int    ret;    

        host = gethostbyname( pAddr );
        
        ZeroMemory( &sa, sizeof(sa) );
        sa.sin_family      = AF_INET;
        sa.sin_port        = htons(port);         
//        sa.sin_addr.s_addr = inet_addr( pAddr );  
여기서 에러 ->sa.sin_addr        = *((struct in_addr *)host->h_addr_list[0]);            
        
        ret = connect( g_socket, (struct sockaddr *)&sa, sizeof(struct sockaddr));
        if( ret == SOCKET_ERROR )
        {
                if( WSAEWOULDBLOCK == WSAGetLastError() )
                        return TRUE;

                return FALSE;
        }
        return TRUE;
}

BOOL RecvMsg( SOCKET ClientSocket, char *recvbuf, HWND hwnd )
{    
        unsigned long recvsize, i ;
        int           recvbyte;        


        if( (ioctlsocket( ClientSocket, FIONREAD, &recvsize ) == 0 ) && (recvsize > 0 ) )
        {
                if( recvbuf != NULL )
                        ZeroMemory( g_recvbuf, 256 );
                
                for( i = 0; i < recvsize; )
                {
                        recvbyte = recv( ClientSocket, recvbuf + i, recvsize, 0 );            
                        if( recvbyte > 0 )
                        {
                                i += (unsigned long)recvbyte;
                                recvsize = recvsize - recvbyte ;
                        }
                        else
                        {

                        }
                }
        }

    return TRUE;
}

BOOL SendMsg( SOCKET ClientSocket, char *sendbuff, int size )
{        
        int ret;

        ret = send( ClientSocket, sendbuff, size, 0 );
        if( ret == SOCKET_ERROR )              
        {  
                AfxMessageBox( "SendMsg() -> send( ) 함수 실패... " );
                return FALSE;
        }

        return TRUE;

}

강사님이 이해하라고 쳐준 소스인데 저 부분에서 에러가 납니다.
왜 에러가 나는지 이유를 몰라서 그럽니다.

댓글 '2'

여치

2002.10.20 01:16:05
*.207.79.133

무슨 에러가 나는데요?

hongiro

2002.10.20 01:24:08
*.243.40.166

unhandled exception in socket07.exe : 0xc00000005 |access violation
host 는 0번지를 가르키고 있습니다.
파일 첨부

여기에 파일을 끌어 놓거나 파일 첨부 버튼을 클릭하세요.

파일 크기 제한 : 0MB (허용 확장자 : *.*)

0개 첨부 됨 ( / )
List of Articles
번호 제목 글쓴이 날짜sort 조회 수
43 오랜만에 질문 하나 드립니다~ 풍이 2003-08-07 7076
42 [re] [질문] 게임 [2] hongiro 2003-07-08 6647
41 [re] [질문] 게임 [1] 여치 2003-07-08 9830
40 [질문] 게임 hongiro 2003-07-07 12307
39 [퍼온글] 프로그래밍의 도 여치 2003-06-20 6200
38 NPC 길찾기 시스템과 맵구조에 대한 질문이에요 ^^ [2] 풍이 2003-06-03 7598
37 [펌] 어릴적 기억 [1] 청년 2003-03-18 6276
36 마소의 도전...X-box의 후기 베지타 2003-01-15 9135
35 swicth 문에 대한 질문 [2] hongiro 2002-11-14 6419
34 [re] direct3d8.0 여치 2002-11-07 5541
33 direct3d8.0 hongiro 2002-11-07 14364
32 [필독] 프로그래밍, 신이 내린 최고의 노가다 [1] 베지타 2002-10-21 7864
31 [re] 지금 게임학원에 [1] 여치 2002-10-20 6192
30 [re] 소켓 [1] 여치 2002-10-20 5836
29 지금 게임학원에 hongiro 2002-10-20 6344
» [re] 소켓 [2] hongiro 2002-10-19 5839
27 멀티스레드 프로그래밍에서 동기화는 왜 필요할까? [1] 여치 2002-10-19 5961
26 가상함수는 어떻게 호출되나? 여치 2002-10-19 6700
25 메모리카피는 어떻게 이루어지나? [3] 여치 2002-10-19 9597
24 정밀한 퍼포먼스 체크 여치 2002-10-19 7208



XE Login

天安門大屠殺 六四天安門事件 反右派鬥爭 大躍進政策 文化大革命 六四天安門事件 The Tiananmen Square protests of 1989 天安門大屠殺 The Tiananmen Square Massacre 反右派鬥爭 The Anti-Rightist Struggle 大躍進政策 The Great Leap Forward 文化大革命 The Great Proletarian Cultural Revolution 人權 Human Rights 民運 Democratization 自由 Freedom 獨立 Independence 多黨制 Multi-party system 民主 言論 思想 反共 反革命 抗議 運動 騷亂 暴亂 騷擾 擾亂 抗暴 平反 維權 示威游行 法輪功 Falun Dafa 李洪志 法輪大法 大法弟子 強制斷種 強制堕胎 民族淨化 人體實驗 胡耀邦 趙紫陽 魏京生 王丹 還政於民 和平演變 激流中國 北京之春 大紀元時報 九評論共産黨 獨裁 專制 壓制 統一 監視 鎮壓 迫害 侵略 掠奪 破壞 拷問 屠殺 肅清 活摘器官 障テ社會 誘拐 買賣人口 遊進 走私 毒品 賣淫 春畫 賭博 六合彩 台灣 臺灣 Taiwan Formosa 中華民國 Republic of China 西藏 土伯特 唐古特 Tibet 達償ワ喇嘛 Dalai Lama 新疆維吾爾自治區 The Xinjiang Uyghur Autonomous Region free tibet