使用 client/server 计算器 C++ 时遇到问题

Having trouble with client/server calculator C++

我是编码新手,我必须使用这个 client/server 计算器来参加我的大学课程考试。 不幸的是,我的教授并没有向我们解释什么,所以我必须自己做所有的工作。

我已经编写了程序的连接部分并且工作正常,实际上客户端可以连接到服务器。

我面临的问题是服务器中应该从客户端接收整数的函数。 问题是我从客户端发送到服务器的任何数字都只到达 0。 我知道是因为我使用 cout 来显示函数后的值。

服务器端函数:

void ricezione_interi(int intero, int csock){
int bytesRecv = recv(csock, &intero, sizeof(int), 0);
if (bytesRecv == -1)
{
    cout << "Connection issue." << endl;
    close(csock);
    exit(1);
}
if (bytesRecv == 0)
{
    cout << "Client disconnected." << endl;
    close(csock);
    exit(1); 
}

return; }

客户端代码:

int bytesSent = send(sock, &intero, sizeof(int), 0); 

    if (bytesSent == -1)
    {
        cerr << "There was a connection issue." << endl;
        break;
    }
    if (bytesSent == 0)
    {
        cout << "Disconnected." << endl; 
        break;
    } 

这段代码有什么问题? 感谢提前关注

此致。

The problem is that whatever number I send from the client, to the server only arrives 0.

没有 MCVE,我只能猜测是什么问题。所以这是我的猜测...

你的接收函数所做的与

大致相同
void foo(int x) {
    x = 24;
}

当你调用它时

int main() {
    int y = 0;
    foo(y);
    std::cout << y;
}

然后你将得到 0 作为输出。原因是x是按值传递的。如果你想让函数修改它的参数,你必须通过引用传递它:

void foo(int& x) {   // note the &
     x = 24;
}
int main() {
    y = 0;
    foo(y);
    std::cout << y;
}

这将打印 24

PS:请注意,此答案纯属猜测。我不知道你是怎么知道这个值总是 0 的,我不得不猜测。在询问有关代码的问题时,重要的是包括一个最小的完整且可验证的示例以及预期输出以及问题中的实际输出。