一個win32平臺的socket簡單程序

最新學習了下win32平臺以及linux平臺的socket程序編寫,發現2者的差異不是很大,就是傳輸數據的時候調用的函數不一樣 基本流程都是大同小異,下面貼下本身寫的一個比較簡單的socket程序,
 
服務器端:
#include <stdio.h>
#include <WINSOCK2.H>


int main()
{
  WORD wVersionRequested;
  WSADATA wsaData;
   int err;
    
  wVersionRequested = MAKEWORD( 1, 1 );
    
  err = WSAStartup( wVersionRequested, &wsaData );
   if ( err != 0 ) {
     return 1;
  }
    
   if ( LOBYTE( wsaData.wVersion ) != 1 ||
                HIBYTE( wsaData.wVersion ) != 1 )    
  {                                                                
    WSACleanup( );
     return 1;    
  }
        
        SOCKET socket_srv = socket(AF_INET,SOCK_STREAM,0);
   struct sockaddr_in        soc_addrs,soc_addrc ;
   int    soc_lens = sizeof(sockaddr);
   int    soc_lenc = sizeof(sockaddr);
   char buffer[100];
        soc_addrs.sin_addr.S_un.S_addr = inet_addr( "127.0.0.1");
  soc_addrs.sin_family = AF_INET;
  soc_addrs.sin_port = htons(6000);
  bind(socket_srv,(SOCKADDR *) &soc_addrs,soc_lenc);
  listen(socket_srv,10);
   while ( 1 )
  {
    SOCKET socket_client = accept(socket_srv,(SOCKADDR*)&soc_addrc,&soc_lenc);
    recv(socket_client,buffer,100,0);
    printf( "%s\n",buffer);
                closesocket( socket_client);
  }

  WSACleanup();
     return 0;
}
 
 
客戶端:
#include <stdio.h>
#include <WINSOCK2.H>


int main()
{
  WORD wVersionRequested;
  WSADATA wsaData;
   int err;
    
  wVersionRequested = MAKEWORD( 1, 1 );
    
  err = WSAStartup( wVersionRequested, &wsaData );
   if ( err != 0 ) {
     return 1;
  }
    
   if ( LOBYTE( wsaData.wVersion ) != 1 ||
                HIBYTE( wsaData.wVersion ) != 1 )    
  {                                                                
    WSACleanup( );
     return 1;    
  }
        
   struct sockaddr_in    sco_addr;
   int len = sizeof(SOCKADDR);
   char buffer[100] = { "welcome to http://wiliiwin.blog.51cto.com/"};
  sco_addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
  sco_addr.sin_family = AF_INET;
  sco_addr.sin_port = htons(6000);
        SOCKET scoke_client = socket(AF_INET,SOCK_STREAM,0);
  while (1)
  {
    connect(scoke_client,(SOCKADDR*)&sco_addr,len);
            send(scoke_client,buffer,100,0);
    closesocket(scoke_client);
  }
  WSACleanup();
  return 0;
}
 
此程序就是客戶端向服務器端發送一個字符串,服務端會接收到這個字符串,服務端要是現實出接受的字符串,就說明程序已經實現了網絡通訊.
相關文章
相關標籤/搜索