WinSock UDP 短连接

2021-01-18 12:33

阅读:507

标签:else   cout   net   nta   ble   短连接   tle   sendto   lse   

服务端:socket -> bind -> sento/recvfrom -> close
客户端: socket -> sendto/recvfrom -> close


服务端:

#include
#include
#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 

客户端:

#include
#include
#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 > buf;
        sendto(ClientSocket, buf, sizeof(buf), 0, (SOCKADDR *)&ClientAddr, sizeof(ClientAddr));
        recvfrom(ClientSocket, buf, sizeof(buf), 0, (SOCKADDR *)&ClientAddr, &ClientAddrLen);

        cout 

WinSock UDP 短连接

标签:else   cout   net   nta   ble   短连接   tle   sendto   lse   

原文地址:https://www.cnblogs.com/zpchcbd/p/12177554.html


评论


亲,登录后才可以留言!