mardi 24 novembre 2020

String is cut in the process of manipulating it

I want to print out something like

"Socket No 3 : Hello world" "Socket No 4 : Hello hello!"

each client only types what they want to say, but from the server side, it adds which socket number each client is.

But if I type something more and more, it loses the messages from the client side or prints out weird squares like this:

================================================

new connection from 127.0.0.1 on port 65272 Socket No 3 : ���Socket No 3 : fdsklj

================================================

Did I mess up with memory management?

void send_to_all(int j, int i, int sockfd, int nbytes_recvd, char *recv_buf, fd_set *master)
{
    if (FD_ISSET(j, master)){
        if (j != sockfd && j != i) {
            if (send(j, recv_buf, nbytes_recvd, 0) == -1) {
                perror("send");
            }
        }
    }
}

void send_recv(int i, fd_set *master, int sockfd, int fdmax)
{
    int nbytes_recvd, j;
    char recv_buf[BUFSIZE];

    // int sockfd -> char* sockfd_char

    std::string sockfd_string = "";

    sockfd_string = std::to_string(sockfd);
    sockfd_string = "Socket No " + sockfd_string;

    sockfd_string = sockfd_string + " : ";
    sockfd_string = sockfd_string + std::string(recv_buf);


    char* sockfd_char = new char[sockfd_string.length() + 1];
    strcpy(sockfd_char, sockfd_string.c_str());

    if ((nbytes_recvd = recv(i, recv_buf, BUFSIZE, 0)) <= 0) {
        if (nbytes_recvd == 0) {
            printf("socket %d hung up\n", i);
        }else {
            perror("recv");
        }
        close(i);
        FD_CLR(i, master);
    } else {
        for(j = 0; j <= fdmax; j++){
            send_to_all(j, i, sockfd, strlen(sockfd_char), sockfd_char, master);
        }
    }
    delete[] sockfd_char;
}

Aucun commentaire:

Enregistrer un commentaire