服务器java 客户端c,C ++服务器和Java客户端聊天

本文探讨了一个C++服务器与Java客户端在消息传递过程中遇到的问题。当发送消息‘helloworld’时,服务器收到并打印出‘Client:helloworldClient’。问题在于服务器的read()函数在接收到空消息时返回0,导致额外显示了‘Client:’。此外,跨平台通信中,行分隔符不一致也可能造成混乱。解决方法包括正确处理read()的返回值和确保两端的行分隔符匹配。
摘要由CSDN通过智能技术生成

;)

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);

}

}

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

ps.println(msg);

where ps is a printstream.

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!

解决方案

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

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.

In addition, be aware that:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值