C ++服务器和Java客户端聊天 [英] C++ server and java client chat

查看:129
本文介绍了C ++服务器和Java客户端聊天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

;)

我用c ++服务器和Java客户端编写了一个聊天程序.

I write a chat program with c++ server and java client.

负责从客户端接收消息的功能的代码为:

The code of the function that responsible to receiving messages from the client is:

void *recieve(void* *v)
{
    while (true)
    {
        bzero(buffer, 256);
        n = read(socketfd, buffer, 256);
        if (n < 0)
            exit(1);
        printf("Client: %s", buffer);
    }
}

负责向服务器发送消息的thar函数的代码仅是:

the code of the function thar responsible to send messages to the server is just:

ps.println(msg);

其中ps是打印流.

当我向服务器发送消息时,在c ++服务器打印上说"hello world": 客户端:你好worldClient".

When I send a message to the server, say "hello world" the c++ server print: "Client: hello worldClient".

如果有人可以帮助我,我将不胜感激. (如果我的英语不好,我深表歉意) 谢谢!

I would appreciate if someone could help me with this. (I apologize if my English is not good) thanks!

推荐答案

read() 函数到达文件末尾时将返回0.

The read() function will return 0 when it reaches the end of file.

因此,在您的情况下,有一个循环迭代接收了"Hello world",然后又有一个迭代,除了read()返回0外,将不接收任何内容.因此,"Client:"显示为空字符串.

So in your case, there is a first loop iteration that receives "Hello world", then there's one more iteration, that will receive nothing but read() returns 0. So "Client :" is displayed with an empty string.

此外,请注意:

  • 使用基于套接字的通信,不能保证服务器端的一个read()将对应于客户端端的一个println().因此,对于较长的邮件,您将冒着分批接收的风险.然后,在输出中,您会在消息文本中看到几个客户端".
  • 该行分隔符已发送 Java端不一定与服务器端预期的行分隔符相对应,如果您跨平台工作.
  • with socket based communication, it is not guaranteed that one read() on the server side will correspond to one println() on the client side. So for longer messages, you'll risk to receive it in pieces. On the output you'd then see several "Client" within the message text.
  • the line separator sent on the java side might not necessarily correspond to the line separator expected on the server side, expect if you're working cross-platform.

这篇关于C ++服务器和Java客户端聊天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆