2016年6月25日土曜日

WindowsでTCP・IP通信のひな型

サーバー側
#include
#include
int main(){
  SOCKET soc,accpSoc;
  int ret,w_ret,len;
  struct sockaddr_in addr,accpAddr;
  WORD wVersionRequested;
  WSADATA wsaData;
  char buf[256];
  wVersionRequested = MAKEWORD( 2, 2 );

  //0.Setup
  ret = WSAStartup( wVersionRequested, &wsaData );
  if ( ret != 0 ) {
    /* Tell the user that we could not find a usable */
    /* WinSock DLL.                                  */
 printf("fail startup");
    return -1;
  }
 
  //1.ソケット作成
  soc = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

  //2.bind
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = inet_addr("0.0.0.0");
  addr.sin_port = htons(5150);
  ret = bind( soc,(SOCKADDR*) &addr, sizeof(addr) );

  if(ret == 0){
 printf("success bind\n");
  }
  else{
 w_ret = WSAGetLastError();
 printf("fail bind error code(%d)\n",w_ret);
 return w_ret;
  }
  
  //3.listen
  ret = listen(soc,1);

  if(ret == 0){
 printf("success listen\n");
  }
  else{
 w_ret = WSAGetLastError();
 printf("fail listen error code(%d)\n",w_ret);
 return w_ret;
  }

  //4.accept
  accpSoc = accept(soc,NULL,NULL);
  printf("accept socket");
  
  //5.receive
  while(1){
 len = recv(accpSoc,buf,sizeof(buf),0);
 w_ret = WSAGetLastError();
 if(len <= 0){

   break;
 }
 printf("recv message length = %d\n",len);
  }
  
  //6.後始末

  if ( LOBYTE( wsaData.wVersion ) != 2 ||
    HIBYTE( wsaData.wVersion ) != 2 ) {
    /* Tell the user that we could not find a usable */
    /* WinSock DLL.                                  */
    WSACleanup( );
    return 0; 
  }
  else{
 return -1;
  }
 
}

クライアント側
#include
#include
int main(){

  SOCKET soc;
  int ret,w_ret;
  struct sockaddr_in addr;
  WORD wVersionRequested;
  WSADATA wsaData;
  char* message = "hoge";
  //0.準備
  ret = WSAStartup( wVersionRequested, &wsaData );
  if ( ret != 0 ) {
    /* Tell the user that we could not find a usable */
    /* WinSock DLL.                                  */
 printf("fail startup");
    return -1;
  }
  
  //1.ソケット作成
  soc = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

  //2.接続
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  addr.sin_port = htons(5150);

  if ( connect( soc, (SOCKADDR*) &addr, sizeof(addr) ) == SOCKET_ERROR) {
    printf( "Failed to connect.\n" );
    WSACleanup();
    return -1;
  }


  //3.送信
  while(1){
 send(soc,message,sizeof(message),0);
 Sleep(1000);
  }
  //4.後始末
  WSACleanup();  
  return 0;
}

0 件のコメント:

コメントを投稿