Echo server C + + 4-UDP connect version

Calling the connect function for a UDP socket does not establish a connection with the UDP socket of the other party, but registers the destination IP and port information with the UDP socket.

Modify client code

The server code does not need to be modified, just the client code. After you call the connect function, you can call the write and read functions to send and receive data without calling the sendto and recvfrom functions.

include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

const int BUF_SIZE = 30;

void error_handling(const char *message);

// Receive two parameters, argv[1] is the IP address and argv[2] is the port number
int main(int argc, char *argv[]) {
    int sock;
    char message[BUF_SIZE];
    ssize_t str_len;

    struct sockaddr_in server_addr;

    if (argc != 3) {
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }

    sock = socket(PF_INET, SOCK_DGRAM, 0);
    if (sock == -1) {
        error_handling("socket() error");
    }

    // Address information initialization
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET; // IPV4 address family
    server_addr.sin_addr.s_addr = inet_addr(argv[1]); // Server IP address
    server_addr.sin_port = htons(atoi(argv[2])); // Server port number

    while (1) {
        fputs("Insert message(q or Q to quit): ", stdout);
        fgets(message, BUF_SIZE, stdin);

        // If you enter Q or Q, exit
        if (!strcmp(message, "q\n") || !strcmp(message, "Q\n")) {
            break;
        }

        write(sock, message, strlen(message));
        str_len = read(sock, message, sizeof(message) - 1);
        message[str_len] = 0;
        printf("Message from server: %s", message);
    }
    close(sock);

    return 0;
}

Project code

github

Reference resources

TCP/IP network programming

Tags: C++ socket github network Programming

Posted on Wed, 04 Dec 2019 01:07:58 -0500 by dzoddi