【问题标题】:Sending messages from C server to Java client从 C 服务器向 Java 客户端发送消息
【发布时间】:2016-07-13 12:41:02
【问题描述】:

我正在尝试将字符串数组 (char ** topics) 从 C 服务器发送到 Java 客户端。显然,服务器正确发送了主题,但客户端没有收到它们。

/* SERVER */
while (*topics != NULL) {
    printf("  > Sending topic '%s'.. ", *topics);
    if(write(sd, *topics, sizeof(*topics)) == -1) {
        perror("write");
        exit(1);
    }
    printf("[OK]\n");

    topics++;
}

客户端如下所示:

/* 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);
    }
  }

客户端显示

s> Current Topics:

一直在等待...:/

【问题讨论】:

  • 您可能想了解 C 中的 sizeof 运算符。
  • C 服务器是否通过流发送换行符?这就是 readLine 在 Java 中所阻止的。
  • Wireshark.......................
  • 服务器正确发送主题”你是如何验证这一点的?
  • 添加最后一个 write(sd, '\n', 1); 并获得启发。

标签: java c sockets tcp


【解决方案1】:
write(sd, *topics, sizeof (*topics))
  1. topics 是一个char**,所以*topics 是一个指向char 的指针。因此,sizeof *topics 是该指针的大小,取决于您的体系结构,为 2 或 4 或 8 个字节。这不是你想要的。你想要strlen(*topics),假设这些是以null结尾的字符串。

  2. 当您在接收器中读取行时,您需要在发送器中发送行。除非数据中已经包含换行符,否则需要在发送者中添加一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多