基于UDP的回声服务器端/客户端

server.c

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
#define Buff_len 1024

int main()
{
    WSADATA wsadata;
    WSAStartup(MAKEWORD(2, 2), &wsadata);

    SOCKET server_sock = socket(AF_INET, SOCK_DGRAM, 0);

    SOCKADDR_IN server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_addr.sin_port = htons(1234);
    bind(server_sock, (SOCKADDR *)&server_addr, sizeof(server_addr));
    char Buff[Buff_len];

    while (1)
    {
        SOCKADDR client_addr;
        memset(&client_addr, 0, sizeof(client_addr));
        int nsize = sizeof(client_addr);
        int len = recvfrom(server_sock, Buff, Buff_len, 0, (SOCKADDR *)&client_addr, &nsize);
        sendto(server_sock, Buff, len, 0, (SOCKADDR *)&client_addr, nsize);
    }
    closesocket(server_sock);

    WSACleanup();
    return 0;
}

client.c

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
#define Buff_len 1024
int main()
{
    WSADATA wsadata;
    WSAStartup(MAKEWORD(2, 2), &wsadata);

    SOCKET client_sock = socket(AF_INET, SOCK_DGRAM, 0);

    SOCKADDR_IN server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_addr.sin_port = htons(1234);
    char Buff[Buff_len];
    while (1)
    {
        memset(Buff, 0, Buff_len);
        printf("请输入:");
        scanf("%s", Buff);
        sendto(client_sock, Buff, Buff_len, 0, (SOCKADDR *)&server_addr, sizeof(server_addr));
        memset(Buff, 0, Buff_len);
        SOCKADDR fromaddr;
        int nsize = sizeof(fromaddr);
        memset(&fromaddr, 0, sizeof(fromaddr));
        recvfrom(client_sock, Buff, Buff_len, 0, &fromaddr, &nsize);
        printf("收到数据:%s\n", Buff);
    }

    closesocket(client_sock);
    WSACleanup();
    return 0;
}

你可能感兴趣的:(Socket编程,计算机网络)