学习内容,参见《Windows网络编程》第7章 Winsock基础
与TCP流式协议不同,UDP为数据报协议。
服务端接受数据,客户端发送数据。
UDP服务端流程
- Socket或WSASocket建立套接字,用SOCK_DGRAM标志。
- bind绑定到IP地址和端口。
- recvfrom/WSARecvFrom接受数据。
UDP客户端流程
UDP客户端有两种方式,一种为无连接,一种为创建虚拟连接。
方式一 无连接
- Socket或WSASocket建立套接字,用SOCK_DGRAM标志。
- 设置服务器地址和端口。
- sento/WSASendTo发送数据。
方式二 建立虚拟连接
- Socket或WSASocket建立套接字,用SOCK_DGRAM标志。
- 设置服务器地址和端口。
- connect连接服务端。
- 调用send发送数据。
使用windows的Winsock 2编程,需要进行工程配置。
- 工程右键Properties->ConfigurationProperties->Linker->Input->Additional Dependencies中添加ws2_32.lib。
- Demo代码采用Multi-Byte方式,设置Properties->ConfigurationProperties->General->Character Set为Use Multi-Byte Character Set。
备注:所有关系到收发数据的缓冲都属于简单的char类型,这些函数没有Unicode版本。当字符集为Unicode时,需要进行字符串转换。
服务端源码,UDPServer.cpp。
// UDPServer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <WinSock2.h>
#include <stdio.h>
#include <stdlib.h>
#define DEFAULT_PORT 5150
#define DEFAULT_COUNT 5
#define DEFAULT_BUFFER_LENGTH 4096
int iPort = DEFAULT_PORT;
DWORD dwCount = DEFAULT_COUNT;
DWORD dwLength = DEFAULT_BUFFER_LENGTH;
BOOL bInterface = FALSE;
char szIterface[32];
//Print usage information and exit
void usage()
{
printf("usage:sender[-p:int][-i:IP][-n:x][-b:x]\n\n");
printf(" -p:int Local port\n");
printf(" -i:IP Local IP address to listen on\n");
printf(" -n:x Number of times to send message\n");
printf(" -b:x Size of buffer to send \n\n");
ExitProcess(1);
}
//ValidateArgs
void ValidateArgs(int argc, _TCHAR** argv)
{
for (int i = 1; i < argc; i