WinSock UDP 短连接
Posted zpchcbd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WinSock UDP 短连接相关的知识,希望对你有一定的参考价值。
服务端:socket -> bind -> sento/recvfrom -> close
客户端: socket -> sendto/recvfrom -> close
服务端:
#include<WinSock2.h>
#include<iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main(int argc, char * argv[]) {
const int BUFSIZE = 1024;
SOCKET ServerSocket;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
WSADATA wsaData;
char buf[BUFSIZE];
int ret;
if ((ret = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0) {
cout << "WSAStartup调用失败" << endl;
return -1;
}
//创建套接字socket
if((ServerSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) {
cout << "创建套接字失败" << WSAGetLastError() << endl;
WSACleanup();
return -1;
}
//绑定套接字
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
ServerAddr.sin_port = htons(atoi(argv[1]));
if(bind(ServerSocket, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr)) == SOCKET_ERROR) {
cout << "绑定套接字失败 " << WSAGetLastError() << endl;
closesocket(ServerSocket);
WSACleanup();
return -1;
}
int ClientLen = sizeof(ClientAddr);
cout << "端口:" << argv[1] << "正在接收数据...." << endl;
while (true) {
//接收数据
ZeroMemory(buf, sizeof(buf));
if ((ret = recvfrom(ServerSocket, buf, sizeof(buf), 0, (SOCKADDR *)&ClientAddr, &ClientLen)) == SOCKET_ERROR) {
cout << "接收数据失败" << WSAGetLastError() << endl;
closesocket(ServerSocket);
WSACleanup();
return -1;
}
else {
//发送数据
cout << "服务端: " << buf << endl;
sendto(ServerSocket, buf, sizeof(buf), 0, (SOCKADDR *)&ClientAddr, ClientLen);
}
}
closesocket(ServerSocket);
WSACleanup();
return 0;
}
客户端:
#include<WinSock2.h>
#include<iostream>
#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable:4996) //忽略旧函数使用缺陷的警告
using namespace std;
int main(int argc, char * argv[]) {
const int BUFSIZE = 1024;
WSADATA WSAData;
SOCKET ClientSocket;
SOCKADDR_IN ClientAddr;
char buf[BUFSIZE];
WSAStartup(MAKEWORD(2, 2), &WSAData);
//创建套接字
ClientSocket = socket(AF_INET,SOCK_DGRAM , IPPROTO_UDP);
ClientAddr.sin_addr.s_addr = inet_addr(argv[1]);
ClientAddr.sin_port = htons(atoi(argv[2]));
ClientAddr.sin_family = AF_INET;
int ClientAddrLen = sizeof(ClientAddr);
//发送数据
while (true) {
ZeroMemory(buf, sizeof(buf));
cout << "客户端: ";
cin >> buf;
sendto(ClientSocket, buf, sizeof(buf), 0, (SOCKADDR *)&ClientAddr, sizeof(ClientAddr));
recvfrom(ClientSocket, buf, sizeof(buf), 0, (SOCKADDR *)&ClientAddr, &ClientAddrLen);
cout << "服务端: " << buf << endl;
}
closesocket(ClientSocket);
WSACleanup();
return 0;
}
以上是关于WinSock UDP 短连接的主要内容,如果未能解决你的问题,请参考以下文章