V
V
vadim64462021-11-25 08:43:18
C++ / C#
vadim6446, 2021-11-25 08:43:18

Why is the socket not reading data correctly?

Good afternoon! I wrote a simple socket and I'm trying to get data from clients (I output the data to the terminal). Everything works, but some nonsense is displayed. Tell me, please, where to dig to fix this? The number of bytes read seems to be correct, but the value is not

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<errno.h>

using namespace std;

int debug = 1;
int socketPort = 9090;

int main(){
    int listenfd = 0, connfd = 0;
    struct sockaddr_in serv_addr;
    char sendBuff[4096];

    listenfd = socket(AF_INET, SOCK_STREAM, 0); 
    memset(&serv_addr, '0', sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(socketPort);
    int enable = 1;
    if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {
        if (debug == 1) {
            perror("Main: http setsockopt error");
        }
    }
    if (bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
        if (debug == 1) {
            perror("Main: http bind error");
        }
    }
    listen(listenfd, 2048);
    std::cout<<"listen port "<<socketPort<<"..."<<endl;
    while(1) {
        connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
        if (connfd < 0) {
            if (debug == 1) {
                perror("Main: http accept error");
            }
            sleep(1);
            continue;
        }
        while (1){
            int ret = recv(connfd , sendBuff , 4096, 0);
            if(ret <= 0) break;

            std::cout<<"size buffer: "<<ret<<endl;
            std::cout<<"value buffer: "<<sendBuff<<endl;
        }
        close(connfd);
    }
    return 0;
}


This is what comes up in the terminal:

[email protected]test-server:/test# ./main
listen port 9090...
size buffer: 263
value buffer: �
size buffer: 214
value buffer: �
size buffer: 213
value buffer: �
size buffer: 263
value buffer: �
size buffer: 214
value buffer: �
size buffer: 213
value buffer: �
size buffer: 263
value buffer: �
size buffer: 214
value buffer: �

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pinkman, 2021-11-25
@famousman204

headings can lie in the buffer. What is the client sending?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question