1. 程式人生 > >VC環境下UDP Socket程式設計示例

VC環境下UDP Socket程式設計示例

 VC下的Socket程式設計要包含winsock2.h標頭檔案,並在專案設定中加入連結庫ws2_32.lib.下面是一個用UDP實現的echo程式示例。 伺服器端程式碼:

#include <stdio.h>
#include <Winsock2.h>

void main()
{
   SOCKET socket1;
   WSADATA wsaData;
   if (WSAStartup(MAKEWORD(2,1),&wsaData)) //呼叫Windows Sockets DLL
    {
         printf("Winsock無法初始化!n");
         WSACleanup();
         return;
    }
   struct sockaddr_in local;
   struct sockaddr_in from;
   int fromlen =sizeof(from);
   local.sin_family=AF_INET;
   local.sin_port=htons(27015); ///監聽埠
   local.sin_addr.s_addr=INADDR_ANY; ///本機

   socket1=socket(AF_INET,SOCK_DGRAM,0);
   bind(socket1,(struct sockaddr*)&local,sizeof(local));
   while (1)
   {
      char buffer[1024]="";
      printf("waiting-------------n");
     if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&from,&fromlen)!=SOCKET_ERROR)
  {
        printf("Received datagram from %s--%sn",inet_ntoa(from.sin_addr),buffer);
        sendto(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&from,fromlen);

  }
   }
   closesocket(socket1);
}

客戶端程式碼:

#include <stdio.h>
#include <Winsock2.h>

void main()
{
   SOCKET socket1;
   WSADATA wsaData;
   if (WSAStartup(MAKEWORD(2,1),&wsaData)) //呼叫Windows Sockets DLL
    {
         printf("Winsock無法初始化!n");
         WSACleanup();
         return;
    }
   struct sockaddr_in server;
   int len =sizeof(server);
   server.sin_family=AF_INET;
   server.sin_port=htons(27015); ///server的監聽埠
   server.sin_addr.s_addr=inet_addr("127.0.0.1"); ///server的地址
   printf("connect the server...n");
   socket1=socket(AF_INET,SOCK_DGRAM,0);
   while (1)
   {
      char buffer[1024]="";
      printf("input messagen");
      scanf("%s",buffer);
      if (strcmp(buffer,"bye")==0)
      {
         printf("exitn");
         Sleep(100);
         closesocket(socket1);
         break;
   }

      if(sendto(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&server,len)!=SOCKET_ERROR)
      {
        Sleep(100);
        if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&server,&len) != SOCKET_ERROR)
        printf("echo from server:%sn",buffer);
      }
    }  
}