从 java 向 c++ 发送消息,c++ 客户端收到奇怪的东西

Send message from java to c++, weird stuff received in c++ client

我已经学习了 Java 将近 8 个月,并决定在业余时间学习一些 c++。

我在 Java 中有一个服务器等待客户端连接(C++ 中的客户端)。

当客户端连接时,我在 java 服务器上所做的事情:

  1. 在键盘上输入消息。
  2. 将文本(字符串)转换为字节。
  3. 将字节数组发送到 C++ 客户端。

C++ 客户端在连接时正在做什么:

  1. 声明一个名为 "buff".
  2. 的字符数组
  3. 收到来自 Java 服务器的消息。
  4. 如果接收时没有错误,则打印消息。

Java中的相关代码:

String message;
        byte[] byteArray = new byte[1024];

        while (true) {
            System.out.println("Enter message: ");
            message = sc.nextLine();    // Enter message
            byteArray = message.getBytes("UTF-8");  // Get bytes of message
            out.write(byteArray);   // Send the Message
        }

C++中的相关代码:

std::cout << "Connected!";

while (true)
{
    char buff[1024];

    if (what = recv(u_sock, buff, sizeof(buff), 0) < 0)
    {
        cout << "Error receiving message " << WSAGetLastError() << endl;
    }
    else
    {
        cout << "Message: " << buff << endl;
    }
}

实际问题: 当我从 Java 发送字符串 "asd" 时,我收到了 C++ 中的 "asd" 和一个笑脸,以及文本 winsock2.0。有时我只收到以前的消息而不是当前发送的消息。可能是什么问题? 当我尝试从 C++ 客户端向 Java 服务器发送消息时,它成功了。

接收到的数据不是以NULL结尾的。要解决这个问题,您应该以 NULL 终止它们:

if ((what = recv(u_sock, buff, sizeof(buff)-1, 0)) < 0)
{
    ⋮
}
else
{
    buff[what] = 0;
    cout << buff << endl;
}

I receive the "asd" in C++, AND a smiley, and the text winsock2.0.

没有。那些东西已经在缓冲区中了。这里的问题是您忽略了 recv() 返回的长度。您必须使用它来界定打印的 buff 数量,幸运的是我忘记了如何在 C++ 流中执行此操作。

您还必须检查它是否为零,这意味着对等方关闭了连接。在错误和零情况下,您还应该关闭套接字并跳出循环,除非错误是 EAGAIN/EWOULDBLOCK.