简单UDP服务器端和客户端(源代码)
- //客户端
- #include <iostream>
- #include <stdio.h>
- #include <windows.h>
- #include <string.h>
- using namespace std;
- #pragma comment(lib, "WS2_32.lib")
- class CInitSock
- {
- public:
- CInitSock(int version01 = 2, int versiont02 = 2)
- {
- WORD sockVersion = MAKEWORD(2, 2);
- WSADATA wsaData = {0};
- if (WSAStartup(sockVersion, &wsaData) != 0)
- {
- cout << "initlization failed!" << endl;
- exit(0);
- }
- }
- ~CInitSock()
- {
- WSACleanup();
- }
- };
- CInitSock mysock;
- int const MAX_SIZE = 1024;
- int main()
- {
- char buffer[MAX_SIZE] = "\0";
- sockaddr_in addr = {0};
- int nLen = sizeof(sockaddr_in);
- SOCKET s;
- addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
- addr.sin_family = AF_INET;
- addr.sin_port = htons(4567);
- s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- while (true)
- {
- cout << "Please input send data: " << endl;
- cin >> buffer;
- if ((strcmp(buffer, "quit") == 0) || (strcmp(buffer, "exit")) == 0)
- {
- cout << "process exit...." << endl;
- break;
- }
- sendto(s, buffer, strlen(buffer), 0, (sockaddr*)&addr, sizeof(addr));
- }
- }
- #include <iostream>
- #include <stdio.h>
- #include <windows.h>
- using namespace std;
- #pragma comment(lib, "WS2_32.lib")
- class CInitSock
- {
- public:
- CInitSock(int version01 = 2, int versiont02 = 2)
- {
- WORD sockVersion = MAKEWORD(2, 2);
- WSADATA wsaData = {0};
- if (WSAStartup(sockVersion, &wsaData) != 0)
- {
- cout << "initlization failed!" << endl;
- exit(0);
- }
- }
- ~CInitSock()
- {
- WSACleanup();
- }
- };
- CInitSock mysock;
- int main()
- {
- SOCKET s = 0;
- sockaddr_in sin = {0};
- sin.sin_family = AF_INET;
- sin.sin_port = htons(4567);
- sin.sin_addr.S_un.S_addr = INADDR_ANY;
- s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if (bind(s, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
- {
- cout << "bind failed!" << endl;
- return 0;
- }
- char buffer[1024] = "\0";
- sockaddr_in addr = {0};
- int nLen = 0;
- nLen = sizeof(sockaddr_in);
- cout << "------- now service start -------------" << endl;
- while (true)
- {
- int nRecv = 0;
- cout << "wait to receive data............" << endl;
- nRecv = recvfrom(s, buffer, 1024, 0, (sockaddr*)&addr, &nLen);
- if (nRecv > 0)
- {
- buffer[nRecv] = '\0';
- cout << "receve buffer: " << buffer << endl;
- }
- }
- closesocket(s);
- }