我的TCP套接字服务器未发送和接收

时间:2019-11-27 01:31:39

标签: c

我试图为客户端编写TCP套接字服务器,然后遇到了一些问题。服务器未发送/接收数据。但是,它可以监听并接受新客户。

我已经尝试使用“ nc 127.0.0.1 -l 10001”来测试客户端,并且效果很好。服务器一次可以发送和接收但编码的字符。我做了一些修改,从那时起,我一直看到错误。

退出消息可以在custom.h中声明为注释或删除。

任何想法都会受到赞赏。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/socket.h>
#include <sys/types.h>

#include <arpa/inet.h>
#include <netinet/in.h>

#include "custom.h"

#define PORT 10001
#define MAXIMUM_CONNECTION 20
#define DATA_SIZE 100

int main() 
{
    int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    struct sockaddr_in serverAddr, clientAddr;
    memset(&serverAddr, '\0', sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(PORT);
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
        exitMessage("Failed to address to port");
    }

    if(listen(sock, MAXIMUM_CONNECTION) < 0) {
        exitMessage("Server is deaf could not listen to incoming messages");    
    }

    char buffer[DATA_SIZE], data[DATA_SIZE];

    while(1) {
        memset(buffer, '\0', DATA_SIZE);
        memset(data, '\0', DATA_SIZE);

        socklen_t clientAddrSize = sizeof(clientAddr);

        if(accept(sock, (struct sockaddr *) &clientAddr, &clientAddrSize) < 0) {
            exitMessage("Could not accept new connections");
        }

        if(recv(sock, buffer, DATA_SIZE - 1, 0) < 0) {
            exitMessage("Failed to receive data from client");      
        }

        printf("\nReceived: \'%s\' to client\n", buffer);
        printf("input data for client: ");

        int index = 0;
        while((data[index++] = getchar()) != '\n');

        if(send(sock, data, strlen(data), 0) < 0) {
            exitMessage("Failed sending to client");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您监听的套接字仅用于接受新连接,而不用于读取/写入数据。 accept函数返回接受的套接字的文件描述符。那就是您应该打给recvsend的电话。

int newsock;
if((newsock = accept(sock, (struct sockaddr *) &clientAddr, &clientAddrSize)) < 0) {
    exitMessage("Could not accept new connections");
}

if(recv(newsock, buffer, DATA_SIZE - 1, 0) < 0) {
    exitMessage("Failed to receive data from client");      
}

printf("\nReceived: \'%s\' to client\n", buffer);
printf("input data for client: ");

int index = 0;
while((data[index++] = getchar()) != '\n');

if(send(newsock, data, strlen(data), 0) < 0) {
    exitMessage("Failed sending to client");
}