#pragma comment(lib,"ws2_32")
#include <winsock2.h>
#include <iostream>

#define YOURIP "192.168.34.103"
#define YOURPORT 1100


struct App
{
 SOCKET sarr[WSA_MAXIMUM_WAIT_EVENTS];
 HANDLE hEarr[WSA_MAXIMUM_WAIT_EVENTS];
 HANDLE hFileArr[WSA_MAXIMUM_WAIT_EVENTS];
 int now;
};

void connectProc(int index);
void writeProc(int index);
void CloseProc(int index);
void DeleteSocket(int index);
void InitEvent(SOCKET sock);
void SendData(int index);


extern App app;




#include "event.h"

using namespace std;

App app; 

 

void main()
{
 WSADATA wsadata;
 WSAStartup(MAKEWORD(2,2),&wsadata);
 
 SOCKET sock;
 sock = socket(AF_INET, SOCK_STREAM, 0);

 SOCKADDR_IN client = {0,};

 client.sin_addr.s_addr = inet_addr(YOURIP);
 client.sin_family = AF_INET;
 client.sin_port = htons(YOURPORT);
 
 
 InitEvent(sock);
 
 WSAEventSelect(app.sarr[app.now],app.hEarr[app.now],FD_CONNECT);
 connect(sock,(SOCKADDR *)&client,sizeof(client));

 app.now++;

 WSANETWORKEVENTS ev;
 int index;
  
  

 while(1)
 {
  index = WSAWaitForMultipleEvents(app.now,app.hEarr,FALSE,WSA_INFINITE,FALSE);
  index -=  WSA_WAIT_EVENT_0;
  WSAEnumNetworkEvents(app.sarr[index],app.hEarr[index],&ev);

  switch(ev.lNetworkEvents)
  {
  case FD_CONNECT:
   connectProc(index);
   break;
  case FD_WRITE:
   writeProc(index);
   break;
  case FD_CLOSE:
   CloseProc(index);
   break;
  } 
 }
 

 WSACleanup();
}


void connectProc(int index)
{
 SOCKET sock = app.sarr[index];
 DeleteSocket(index);
 
 InitEvent(sock);
  
 WSAEventSelect(app.sarr[app.now], app.hEarr[app.now],FD_WRITE);
 app.now++;
}


void writeProc(int index)
{
 if(app.sarr[index])
 {
  while(1)
  {
   SendData(index);
  }
 }

}


void CloseProc(int index)
{
 WSACloseEvent(app.hEarr[index]);
 closesocket(app.sarr[index]);


 DeleteSocket(index);
}

void DeleteSocket(int index)
{
 app.now--;
 app.hEarr[index] = app.hEarr[app.now];
 app.sarr[index] = app.sarr[app.now];
}


void InitEvent(SOCKET sock)
{
 app.sarr[app.now] = sock;
 app.hEarr[app.now] = WSACreateEvent();
}


void SendData(int index)
{
 char str[100];
 printf("아무거나 입력해봐:\n");
 scanf("%s",str);

 SOCKET sock = app.sarr[index];
 send(sock,str,100,0);
}

'API & MFC > 네트워크프로그래밍' 카테고리의 다른 글

우아한 종료  (0) 2010.02.09
EventSelect(클)  (0) 2010.02.05
EventSelect(서버)  (0) 2010.02.05
EventSelect란?  (0) 2010.02.05
ASyncSelect 예제  (1) 2010.02.04
소켓통신의 라이브러리 사용 선택 시 고려사항  (0) 2010.02.02
Posted by 아몰라

댓글을 달아 주세요