SOCKET UDP 发送和接受示例代码

头文件以及初始化:

#include <iostream> using namespace std; // socket header #include <WinSock2.h> #pragma comment(lib, "Ws2_32.lib") void main() { // recieve data from WSAStartup WSADATA wsaData; // initialize socket dll int ret = WSAStartup(MAKEWORD(2, 1), &wsaData); if(ERROR_SUCCESS != ret) { cout << "WSAStartup failed." << endl; return; } // TODO : Socket code here WSACleanup(); }

发送端代码:

// socket used to send SOCKET sockSend = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // local address SOCKADDR_IN addrSend; addrSend.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrSend.sin_port = htons(5120); addrSend.sin_family = AF_INET; SOCKADDR_IN addrRecv; // remote address addrRecv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrRecv.sin_port = htons(5000); addrRecv.sin_family = AF_INET; // message buffer CHAR szMsg[10] = ""; // bind the address for sending socket bind(sockSend, (LPSOCKADDR)&addrSend, sizeof(SOCKADDR_IN)); LOOP: // input the message to be sent cout << "Input data: "; cin >> szMsg; // send the message sendto(sockSend, szMsg, 10, 0, (LPSOCKADDR)&addrRecv, sizeof(SOCKADDR_IN)); // whether exit if(*szMsg != 'e') goto LOOP; // close socket closesocket(sockSend);

接收端代码:

// socket used receive SOCKET sockRecv = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // remote address SOCKADDR_IN addrSend; int iLen = sizeof(SOCKADDR_IN); // local address SOCKADDR_IN addrRecv; addrRecv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrRecv.sin_port = htons(5000); addrRecv.sin_family = AF_INET; // message buffer CHAR szMsg[10] = ""; // bind the address for the receiving socket bind(sockRecv, (LPSOCKADDR)&addrRecv, sizeof(SOCKADDR_IN)); LOOP: // receive message recvfrom(sockRecv, szMsg, 10, 0, (LPSOCKADDR)&addrSend, &iLen); // output the receive message cout << "Receive from: " << inet_ntoa(addrSend.sin_addr) << ":" << ntohs(addrSend.sin_port) << endl; cout << "Message: " << szMsg << endl; // whether exit if(*szMsg != 'q') goto LOOP; // close socket closesocket(sockRecv);

你可能感兴趣的:(socket,buffer,dll,input,output)