C:TCP服务器无法接收来自客户端的消息

发布于 2025-01-12 13:02:48 字数 4023 浏览 0 评论 0原文

我是一个C初学者。我想通过 TCP 发送文件。客户端从txt文件中读取内容并将其发送到服务器。读取方法就可以了。它从文件中读取指定的字节。 Send 方法不会抛出任何异常。然而服务器什么也没收到。我尝试了一整天来解决它。我失败了。

请帮我检查一下我的代码有什么问题。

作为评论建议,我再次编辑我的代码。现在有两个问题。一是在客户端循环中,客户端 fread() 和 send() 的返回值前两次都大于 0,而服务器 accept() 仍然处于阻塞状态,没有收到客户端的消息。

第二个问题。在第三个客户端循环中,客户端fread()的返回值仍然大于0,但是send()的返回值是-1。我尝试以二进制模式rb而不是r打开文件。这是同样的问题。

编辑后的客户端代码:

#include <stdio.h>
#include <winsock.h>
#include <time.h>

#pragma comment(lib, "WS2_32.lib")
#define    MAXLINE        1024*4


SOCKET sockClient;// = socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN servAddr;


int main(void) {
    WSADATA wsd;
    FILE *fp;
    int read_len;
    char buf2[MAXLINE];
    time_t t_start, t_end;

    if ((fp = fopen("file.txt", "r")) == NULL) {
        perror("Open file failed\n");
        exit(0);
    }

    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) {
        printf("WSAStartup failed !\n");
        return 1;
    }

    sockClient = socket(AF_INET, SOCK_STREAM, 0);

    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    servAddr.sin_port = htons(5000);

    /* connect the server commanted by guoqingbo*/
    int i_ret = connect(sockClient, (struct sockaddr *) &servAddr, sizeof(struct sockaddr));
    if (-1 == i_ret) {
        perror("Connect socket failed!\n");
        exit(0);
    }

    printf("client starts\n");
    t_start = time(NULL);

    while (1) {
        read_len = fread(buf2, sizeof(char), MAXLINE, fp);
        if (read_len < 0) {
            perror("read data failed\n");
            break;
        } else if (read_len == 0) {
            printf("read finished\n");
        }
        int send_len = send(sockClient, buf2, read_len, 0);
        if (send_len < 0) {
            perror("Send data failed\n");
            exit(0);
        } else if (send_len == 0) {
            printf("send finished\n");
            break;
        }
    }
    t_end = time(NULL);
    printf("The time used %f s\n", difftime(t_end, t_start));
    fclose(fp);
    closesocket(sockClient);
    WSACleanup();
    return 0;
}

编辑后的服务器代码:

#include <stdio.h>
#include <WINSOCK2.H>
#include <strings.h>
#include <stdlib.h>


#pragma comment(lib, "WS2_32.lib")
#define BUF_SIZE    1024*4

SOCKET socketSrv;
SOCKADDR_IN addrSrv;
SOCKADDR_IN addrClient;
char buf[BUF_SIZE];


int main(void) {
    WSADATA wsd;
    int nRet;
    int recv_len;
    FILE *fp;
    if ((fp = fopen("file.txt", "w")) == NULL) {
        perror("Creat file failed");
        exit(0);
    }
    
    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) {
        printf("WSAStartup failed !\n");
        return 1;
    }

    socketSrv = socket(AF_INET, SOCK_STREAM, 0);
    int len = sizeof(SOCKADDR);

    ZeroMemory(buf, BUF_SIZE);
    addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(5000);

    nRet = bind(socketSrv, (SOCKADDR *) &addrSrv, sizeof(SOCKADDR));
    if (SOCKET_ERROR == nRet) {
        printf("bind failed !\n");
        closesocket(socketSrv);
        WSACleanup();
        return -1;
    }

    if (SOCKET_ERROR == listen(socketSrv, 10)) {
        printf("Server Listen Failed: %d", WSAGetLastError());
        exit(1);
    }


    printf("server started..\n");
    while (1) {
        SOCKET m_New_Socket = accept(socketSrv, (SOCKADDR *) &addrClient, &len);
        if (SOCKET_ERROR == m_New_Socket) {
            printf("Server Accept Failed: %d", WSAGetLastError());
            break;
        }
        if (recv_len = recv(socketSrv, buf, BUF_SIZE, 0) < 0) {
            printf("Server Receive Data Failed!");
            break;
        }
        int write_length = fwrite(buf, sizeof(char), recv_len, fp);
        if (write_length < recv_len) {
            printf("File write failed\n");
            break;
        }
    }
    fclose(fp);
    closesocket(socketSrv);
    WSACleanup();
    return 0;
}

I am a C beginner. I want to send a file by TCP. The client reads content from a txt file and sent it to server. Read method is ok. It reads the specified bytes from the file. Send method dose not throw any exception. However the server receives nothing. I try to solve it for a whole day. I fail.

Please help me check what is wrong with my code.

As comment advice, I edit my code again. Now there are two problem. One is that in the client loop the return values from client fread() and send() is greater than 0 for the first two times while the server accept() is still blcoked without getting message from client.

The second problem. In the third client loop, the return value of client fread() is still greater than 0, but the return value of send() is -1.I try to open the file in binary mode rb instead of r. It is the same problem.

the edited client code:

#include <stdio.h>
#include <winsock.h>
#include <time.h>

#pragma comment(lib, "WS2_32.lib")
#define    MAXLINE        1024*4


SOCKET sockClient;// = socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN servAddr;


int main(void) {
    WSADATA wsd;
    FILE *fp;
    int read_len;
    char buf2[MAXLINE];
    time_t t_start, t_end;

    if ((fp = fopen("file.txt", "r")) == NULL) {
        perror("Open file failed\n");
        exit(0);
    }

    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) {
        printf("WSAStartup failed !\n");
        return 1;
    }

    sockClient = socket(AF_INET, SOCK_STREAM, 0);

    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    servAddr.sin_port = htons(5000);

    /* connect the server commanted by guoqingbo*/
    int i_ret = connect(sockClient, (struct sockaddr *) &servAddr, sizeof(struct sockaddr));
    if (-1 == i_ret) {
        perror("Connect socket failed!\n");
        exit(0);
    }

    printf("client starts\n");
    t_start = time(NULL);

    while (1) {
        read_len = fread(buf2, sizeof(char), MAXLINE, fp);
        if (read_len < 0) {
            perror("read data failed\n");
            break;
        } else if (read_len == 0) {
            printf("read finished\n");
        }
        int send_len = send(sockClient, buf2, read_len, 0);
        if (send_len < 0) {
            perror("Send data failed\n");
            exit(0);
        } else if (send_len == 0) {
            printf("send finished\n");
            break;
        }
    }
    t_end = time(NULL);
    printf("The time used %f s\n", difftime(t_end, t_start));
    fclose(fp);
    closesocket(sockClient);
    WSACleanup();
    return 0;
}

the edited server code:

#include <stdio.h>
#include <WINSOCK2.H>
#include <strings.h>
#include <stdlib.h>


#pragma comment(lib, "WS2_32.lib")
#define BUF_SIZE    1024*4

SOCKET socketSrv;
SOCKADDR_IN addrSrv;
SOCKADDR_IN addrClient;
char buf[BUF_SIZE];


int main(void) {
    WSADATA wsd;
    int nRet;
    int recv_len;
    FILE *fp;
    if ((fp = fopen("file.txt", "w")) == NULL) {
        perror("Creat file failed");
        exit(0);
    }
    
    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) {
        printf("WSAStartup failed !\n");
        return 1;
    }

    socketSrv = socket(AF_INET, SOCK_STREAM, 0);
    int len = sizeof(SOCKADDR);

    ZeroMemory(buf, BUF_SIZE);
    addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(5000);

    nRet = bind(socketSrv, (SOCKADDR *) &addrSrv, sizeof(SOCKADDR));
    if (SOCKET_ERROR == nRet) {
        printf("bind failed !\n");
        closesocket(socketSrv);
        WSACleanup();
        return -1;
    }

    if (SOCKET_ERROR == listen(socketSrv, 10)) {
        printf("Server Listen Failed: %d", WSAGetLastError());
        exit(1);
    }


    printf("server started..\n");
    while (1) {
        SOCKET m_New_Socket = accept(socketSrv, (SOCKADDR *) &addrClient, &len);
        if (SOCKET_ERROR == m_New_Socket) {
            printf("Server Accept Failed: %d", WSAGetLastError());
            break;
        }
        if (recv_len = recv(socketSrv, buf, BUF_SIZE, 0) < 0) {
            printf("Server Receive Data Failed!");
            break;
        }
        int write_length = fwrite(buf, sizeof(char), recv_len, fp);
        if (write_length < recv_len) {
            printf("File write failed\n");
            break;
        }
    }
    fclose(fp);
    closesocket(socketSrv);
    WSACleanup();
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文