gpt4 book ai didi

java - 通过网络从 C++ 客户端向 Java 服务器发送字符串

转载 作者:行者123 更新时间:2023-11-30 00:56:51 25 4
gpt4 key购买 nike

我正在编写一个客户端/服务器应用程序,其中客户端是用 C++ 编写的,服务器是 Java 编写的。它们之间的通信是通过 UDP 协议(protocol)进行的。他们需要通过网络交换字符串消息。现在,通信工作很多,客户端发送消息,服务器接收它,但我注意到在 Java 端接收到的字符串就像中继一样。我的意思是,如果我尝试使用以下功能将它显示在控制台上:

System.out.println("This is the message received " 
+ message + " by the client just now");

我得到的结果是:

This is the message received *message*

将字符串“by the client just now”导出。

我认为这是由于 Java 和 C++ 之间存在某些不兼容问题,但我找不到解决方案。

编辑:这是接收器的代码:

byte[] bytes = _packet.getData(); // Datagram Packet
hostName = getStringFromBytes(bytes, 0, 15);

(...)

private String getStringFromBytes (byte[] bytes, int lowerBound, int length)
{
byte[] bufferBytes = new byte[length];
System.arraycopy(bytes, lowerBound, bufferBytes, 0, length);

return new String(bufferBytes).trim();
}

和发件人:

 if(sendto(_socket, buffer, BUFFER_LEN, 0, (struct sockaddr*) &_serverAddress, addressLenght) == -1)
cout << "Trasmission failed!\n" << endl;

其中 buffer 是一个字符数组。

最佳答案

if(sendto(_socket, buffer, BUFFER_LEN, 0, (struct sockaddr*) &_serverAddress, addressLenght) == -1)

这一行似乎表明 buffer 是一个 C 字符串。如果是这种情况,您需要在服务器端解析出额外的 NULL 字符。来自 c 字符串的 NULL 字符可能导致 JAVA 代码在看到 NULL 字符时立即停止处理字符串——这是它应该做的。

您可能只删除 JAVA 代码中字符串的最后一个字符。请记住,C 字符串的末尾总是有一个额外的字符——NULL 字符。

还有,BUFFER_LEN是宏吗?它被定义为什么?尝试只发送实际的缓冲区长度,而不是预定义的长度。

std::string buffer = "Your Message";

if(sendto(_socket, buffer.c_str(), buffer.length(), ...)

一般来说,在 C++ 中,尽可能使用 std::string,而不是 char*。

关于java - 通过网络从 C++ 客户端向 Java 服务器发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9364808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com