Socket之UDP通信例子
UDP通信方式:1,客户端不需要进行连接,而是直接访问服务器通过sendto来发送数据,recvfrom接受数据2,服务端,不需要监听、接受等待客户端请求,当收到客户端socket通过sendto来回应客户端请求。Client端:#include <winsock2.h>#include <iostream>
#pragma comment(lib, "WS2_32.lib")
const unsigned int PORT = 11024;
const int kBufferSize = 1024;
int main() {
WSADATA wsData;
if(WSAStartup(MAKEWORD(2, 2), &wsData) != 0) {
std::cout << "start up failed\n" << std::endl;
return 0;
}
// connect the socket;
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
SOCKADDR_IN addIn;
addIn.sin_family = AF_INET;
addIn.sin_port = htons(PORT);
addIn.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
char cSendBuffer = "Client sends a Message to the Server, please confirm?";
int bRecvLen = sizeof(addIn);
int bSendRet = sendto(s, cSendBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, sizeof(addIn));
while(bSendRet != SOCKET_ERROR) {
char cRecvBuffer = "#";
int bRecv = recvfrom(s, cRecvBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, &bRecvLen);
if(bRecv != SOCKET_ERROR) {
std::cout << "Client recvie the infromation from the server is: " << cRecvBuffer << std::endl;
ZeroMemory(cSendBuffer, kBufferSize);
std::cout << "please input the information the sends to the server: ";
std::cin >> cSendBuffer;
bSendRet = sendto(s, cSendBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, sizeof(addIn));
} else{
break;
}
}
if(WSACleanup() != 0) {
std::cout << "clean up failed\n";
return -1;
}
closesocket(s);
return 0;
}
Server端:#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "WS2_32.lib")
const unsigned int PORT = 11024;
const int kBufferSize = 1024;
int main() {
WSADATA wsData;
if(WSAStartup(MAKEWORD(2, 2), &wsData) != 0) {
std::cout << "start failed" << std::endl;
return -1;
}
//
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
SOCKADDR_IN addIn;
addIn.sin_family = AF_INET;
addIn.sin_port = htons(PORT);
addIn.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int bBindRet = bind(s, (LPSOCKADDR) &addIn, sizeof(addIn));
if(bBindRet != 0) {
std::cout << "bind failed" << std::endl;
return -1;
}
char cRecvBuffer;
int ilen = sizeof(addIn);
int iRecv = recvfrom(s, cRecvBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, &ilen);
while(iRecv != SOCKET_ERROR) {
std::cout << "recvie information: " << std::endl;
char cSendBuffer;
std::cout << "Input the information that the client sends; " << std::endl;
std::cin >> cSendBuffer;
sendto(s, cSendBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, sizeof(addIn));
}
if(WSACleanup() != 0) {
std::cout << "Clean up failed" << std::endl;
return -1;
}
return 0;
}
页:
[1]