基于UDP的socket编程
服务器端:
1、创建socket
2、将套接字绑定到一个本地地址和端口上bind
3、等待接受数据receive from
4、关闭套接字。
代码:
#include <Winsock2.h>
#include <stdio.h>
void main()
{
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;
 
 wVersionRequested = MAKEWORD( 2, 2 );
 
 err = WSAStartup( wVersionRequested, &wsaData );
 if ( err != 0 ) {
  /* Tell the user that we could not find a usable */
  /* WinSock DLL.                                  */
  return;
 }
 
 /* Confirm that the WinSock DLL supports 2.2.*/
 /* Note that if the DLL supports versions greater    */
 /* than 2.2 in addition to 2.2, it will still return */
 /* 2.2 in wVersion since that is the version we      */
 /* requested.                                        */
 
 if ( LOBYTE( wsaData.wVersion ) != 2 ||
        HIBYTE( wsaData.wVersion ) != 2 ) {
  /* Tell the user that we could not find a usable */
  /* WinSock DLL.                                  */
  WSACleanup( );
  return;
 }
 
  SOCKET socketSrv=socket(AF_INET,SOCK_DGRAM,0);
  SOCKADDR_IN addrSrv;
  addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
  addrSrv.sin_family=AF_INET;
  addrSrv.sin_port=htons(6000);
 bind(socketSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
 SOCKADDR_IN addrClient;
 int len=sizeof(SOCKADDR);
 char recvBuf[100];
 recvfrom(socketSrv,recvBuf,100,0,(SOCKADDR*)&addrClient,&len);
 printf("%s\n",recvBuf);
    closesocket(socketSrv);
 WSACleanup();
 
}
 
客户端程序:
1、创建套接字socket
2、向服务器发送数据
3、关闭套接字
代码:
#include <Winsock2.h>
#include <stdio.h>
void main()
{
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;
 
 wVersionRequested = MAKEWORD( 2, 2 );
 
 err = WSAStartup( wVersionRequested, &wsaData );
 if ( err != 0 ) {
  /* Tell the user that we could not find a usable */
  /* WinSock DLL.                                  */
  return;
 }
 
 /* Confirm that the WinSock DLL supports 2.2.*/
 /* Note that if the DLL supports versions greater    */
 /* than 2.2 in addition to 2.2, it will still return */
 /* 2.2 in wVersion since that is the version we      */
 /* requested.                                        */
 
 if ( LOBYTE( wsaData.wVersion ) != 2 ||
        HIBYTE( wsaData.wVersion ) != 2 ) {
  /* Tell the user that we could not find a usable */
  /* WinSock DLL.                                  */
  WSACleanup( );
  return;
 }
 SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0);
    SOCKADDR_IN addrSrv;
 addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
 addrSrv.sin_family=AF_INET;
 addrSrv.sin_port=htons(6000);
 sendto(sockClient,"Hello Visionsky",
  strlen("Hello Visionsky")+1,0,
  (SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
 closesocket(sockClient);
    WSACleanup();
}
注意事项同tcp一样~