1

试图建立一个代理服务器。
从客户端接收 -> 发送到服务器 -> 从服务器接收 -> 发送到客户端。

代理从客户端接收正确的数据。
但在那之后,我从服务器接收了 0 个字节。

这是我应该从客户端接收并发送到服务器的数据包

0A 00 2C 01 23 00 0C 00 B3 01

这是我的代码;

    //intercept commu by server <-> client

    memset(buffer, 0, buffer_len);

    //recv from client
    if((bytecount = recv(*csock, buffer, buffer_len, 0))== -1){
        fprintf(stderr, "Err: receiving data %d\n", errno);
        return 0;
    }

    //display what we got from the client
    printf("Received bytes %d\n", bytecount);
    for ( int i = 0; i < bytecount; i++ ) {
    printf( "%02x ", static_cast<unsigned char>( buffer[i] ) );
    }
    printf("\n");

    //send to server what we got from the client
    if((gbytecount=send(gsock, buffer, buffer_len, 0))== -1){
    fprintf(stderr, "Error sending data %d\n", errno);
    goto FINISH;
    }


    //recv from server
    if((gbytecount = recv(gsock, buffer, buffer_len, 0))== -1){
        fprintf(stderr, "Error receiving data %d\n", errno);
        return 0;
    }

    printf("Received bytes %d\n", gbytecount);
    for ( int i = 0; i < gbytecount; i++ ) {
    printf( "%02x ", static_cast<unsigned char>( buffer[i] ) );
    }
    printf("\n");   

    //send back to client what we got from the server
    if((bytecount = send(*csock, buffer, buffer_len, 0))== -1){
        fprintf(stderr, "Err: sending data %d\n", errno);
        return 0;
    }

从客户端接收后,如何检查代理向服务器发送的内容?
我的逻辑有问题吗?


更新

我想我发现了问题,它是因为 buffer_len。

现在我有 recv() 字节 93。但服务器再次发送另一个数据包。
我该怎么处理我的代码?

目前我的代码是:

recv from client -> send to server -> recv from server -> send to client.

我怎样才能使这个代码像如果客户端/服务器发送一些东西,它会

转发给对方?


更新

必须解决它。谢谢。

4

3 回答 3

2

我不知道你的服务器和客户端,但可能是服务器实际上close是导致 0 的套接字,recv而关闭的原因可能是你bytecount从客户端接收数据但向buffer_len服务器发送数据可能导致一些无效有效数据后的数据发送到服务器!

于 2012-11-30T21:15:54.237 回答
2

You are using blocking calls assuming a direct 1-1 ratio of client->server calls (and vice-versa), but that is almost certainly not going to be the case in a real world application. In reality, the application is going to receive portions of the TCP stream in numerous calls to receive from both the client and the server. You can handle this in two distinct ways. Using select() to see what sockets need to have data read from them, or using an asynchronous library to facilitate the reading/writing to/from the client/server sockets for you.

Since this seems to come up quite a lot, see my answer to this question: How to make a proxy server in C++ using Boost

See the select() API

或者,这是在 boost 中编写一个示例。如果您在 Google 上搜索“boost::asio 代理服务器”,还有许多其他示例。

于 2012-11-30T21:53:03.810 回答
0

BigBoss 的回答是正确的:- 您应该向 gsock 发送 bytecount 字节,而不是发送 buffer_len 字节。更好的是,如果可能,您应该从标头中读取数据包的大小,并尽可能读取那么多字节

于 2012-11-30T21:53:44.030 回答