[re] 소켓

조회 수 5836 추천 수 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
23 [질문]열혈피구 [5] hongiro 2003-09-03 6558
22 [re] 엔진 버전업에 관해 [1] 여치 2003-08-28 6491
21 swicth 문에 대한 질문 [2] hongiro 2002-11-14 6419
20 지금 게임학원에 hongiro 2002-10-20 6343
19 [질문] SS3D의 안보이는 펄리곤 제외 방식 [3] 방문객108 2004-07-01 6303
18 [펌] 어릴적 기억 [1] 청년 2003-03-18 6260
17 캐쉬 적중률 어떻게 측정해요?? ... 2003-11-06 6228
16 [퍼온글] 프로그래밍의 도 여치 2003-06-20 6199
15 [re] 지금 게임학원에 [1] 여치 2002-10-20 6191
14 [re] ss3d 엔진에 대한 질문 [2] 여치 2004-06-13 6159
13 [re] 버텍스버퍼에 캐시를 사용한다는 말이 무슨말인지.. [3] 여치 2003-10-30 6108
12 [re] 엔진 제작기간은? 여치 2003-12-09 6021
11 멀티스레드 프로그래밍에서 동기화는 왜 필요할까? [1] 여치 2002-10-19 5960
» [re] 소켓 [2] hongiro 2002-10-19 5836
9 [re] 소켓 [1] 여치 2002-10-20 5835
8 버텍스버퍼에 캐시를 사용한다는 말이 무슨말인지.. ario 2003-10-28 5751
7 [re] runtime assembler..... gg 2002-09-15 5648
6 [re] direct3d8.0 여치 2002-11-07 5541
5 sse와 정수 레지스터의 연산속도 비교 여치 2002-10-19 5517
4 ss3d 엔진에 대한 질문 Guest 2004-06-13 5410



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