[英]Sending messages from C server to Java client
I'm trying to send an array of string ( char ** topics
) from a C server to a Java client. 我正在尝试从C服务器向Java客户端发送字符串数组(
char ** topics
)。 Apparently, the server sends the topics properly, but the client does not receive them. 显然,服务器正确发送了主题,但是客户端没有收到它们。
/* SERVER */
while (*topics != NULL) {
printf(" > Sending topic '%s'.. ", *topics);
if(write(sd, *topics, sizeof(*topics)) == -1) {
perror("write");
exit(1);
}
printf("[OK]\n");
topics++;
}
The client looks like this: 客户看起来像这样:
/* CLIENT */
static void server_connection() {
String topic = null;
try {
Socket _sd = new Socket(_server, _port); // Socket Descriptor
// Create input stream
DataInputStream _in = new DataInputStream(_sd.getInputStream());
BufferedReader _br = new BufferedReader(new InputStreamReader(_in));
System.out.println("s> Current Topics:");
while ((topic = _br.readLine()) != null) {
System.out.println(topic);
}
if(topic == null) {
System.out.println("Not topics found");
}
// Close socket connection
_out.close();
_in.close();
_sd.close();
} catch(IOException e) {
System.out.println("Error in the connection to the broker " + _server + ":" + _port);
}
}
The client shows 客户端显示
s> Current Topics:
and remains waiting... :/ 并一直在等待...:/
write(sd, *topics, sizeof (*topics))
topics
is a char**
, so *topics
is a pointer to char
. topics
是一个char**
,因此*topics
是一个指向char
的指针。 sizeof *topics
is therefore the size of that pointer, either 2 or 4 or 8 bytes depending on your architecture. 因此,
sizeof *topics
是该指针的大小,根据您的体系结构为2或4或8个字节。 This is not what you want. 这不是您想要的。 You want
strlen(*topics)
, assuming these are null-terminated strings. 您需要
strlen(*topics)
,假设它们是以空字符结尾的字符串。
As you're reading lines in the receiver, you need to send lines in the sender. 在接收方中读取线路时,需要在发送方中发送线路。 Unless the data already contains a newline,, you need to add one in the sender.
除非数据已经包含换行符,否则您需要在发送者中添加一个换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.