无连接通信是通过UDP/IP协议完成的。数据的传输利用数据包,即离散信息包。
- int recvfrom(
- SOCKET s,
- char FAR* buf,
- int len,
- int flags,
- struct sockaddr FAR* from,
- int FAR* fromlen
- );
- int WSARecvfrom(
- SOCKET s,
- LPWSABUF lpBuffers,
- DWORD dwBufferCount,
- LPDWORD lpNumberOfBytesRecvd,
- LPDWORD lpFlags,
- struct sockaddr FAR* lpfrom,
- LPINT fromlen,
- LPWSAOVERLAPPED lpOverlapped,
- LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
- );
创建一个简单的接收端应用程序
- #include<winsock2.h>
- void main(void)
- {
- WSADATA wsaData;
- SOCKET s;
- SOCKADDR_IN Recvaddr;
- SOCKADDR_IN Sendaddr;
- int port = 5050;
- char buffer[1024];
- int buflen = 1024;
- int sendaddrsize = sizeof(Sendaddr);
- WSAStartup(MAKEWORD(2,2), &wsaData);
- s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- Recvaddr.sin_family = AF_INET;
- Recvaddr.sin_port = htons(port);
- Recvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
- bind(s, (SOCKADDR *)&Recvaddr, sizeof(Recvaddr));
- recvfrom(s, buffer, buflen, 0, (SOCKADDR*)&Sendaddr, &sendaddrsize);
- closesocket(s);
- WSACleanup();
- }
发送端
- int sendto(
- SOCKET s,
- const char FAR* buf, //发送数据的缓冲区
- int len, //指明发送多少字节
- int flag,
- const sockaddr FAR* to,
- int tolen
- );
- int WSASendto(
- SOCKET s,
- LPWSABUF lpBuffers,
- DWORD dwBufferCount,
- LPDWORD lpNumberOfBytesSend,
- LPDWORD lpFlags,
- struct sockaddr FAR* lpto,
- LPINT tolen,
- LPWSAOVERLAPPED lpOverlapped,
- LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
- );
简单的发送端程序
- #include <winsock2.h>
- void main(void)
- {
- WSADATA wsaData;
- SOCKET s;
- SOCKADDR_IN addr;
- int port = 5050;
- char buffer[1024];
- int len = 1024;
- WSAStartup(MAKEWORD(2,2), &wsaData);
- s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- addr.sin_family = AF_INET;
- addr.sin_port = htons(port);
- addr.sin_addr.s_addr = inet_addr("123.123.123.123");
- sendto(s, buffer, len, 0, (SOCKADDR*)&addr, sizeof(addr));
- closesocket(s);
- WSACleanup();
- }
因为无连接协议没有连接,所有也不会有对连接的正式关闭和从容关闭。只需要调用closesocket即可释放资源。