如何从java服务器发送字符串到C ++客户端? [英] How to send a string from java server to C++ client?

查看:197
本文介绍了如何从java服务器发送字符串到C ++客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Windows java服务器发送一个字符串到linux c + +客户端,反之亦然,但我写的代码,不工作,我不知道为什么:

I need to send a string from a windows java server to a linux c++ client and vice versa but the code that I wrote, doesn't work and I don't know the why:

Java服务器 Windows上的代码发送字符串

Java server Code on Windows to send a string:

for(int i=0;i<message.length;i++)
{
    message[i]=Byte.parseByte(num_cartella);
}                   
sendData(message,client); 



< >:

Java server code on Windows to receive data:

client = server.accept();
 InputStream ic = client.getInputStream();
 BufferedReader dic = new BufferedReader( new InputStreamReader(ic) );
 String id_scelta=String.valueOf(dic.readLine());

C ++客户端在Linux上的代码发送数据

C++ client code on Linux to send data:

if( send(sock , nCartella,(unsigned)strlen(nCartella), 0) < 0)
{
            cout <<"Invio fallito"<<endl;
            return 1;
}
cout << "Messaggio inviato"<<endl;  

C ++客户端在Linux上的代码接收数据

C++ clientcode on Linux to receive data:

if( recv(sock, server_reply , (unsigned)strlen(server_reply) , 0) < 0)
        {
            cout <<"Ricezione fallita"<<endl;
            return 1;
        }

        cout <<"Risposta server:";
        cout <<server_reply;

为什么它不工作?套接字将创建成功,但客户端和服务器不发送和接收数据,我不知道什么是错误的部分代码

Why it doesn't work? the socket will create with success but client and server doesn't send and receive data and I don't know what is the wrong part of code

推荐答案

你正在绊倒同样的问题,千万在你之前。其中两个,实际上。

You are stumbling on the same problem as thousands before you. Two of them, actually.

第一个问题是,当字符串以这种方式发送时,另一个家伙不知道什么是字符串的长度!所以你需要指出它,并且常见的技术是在实际字符串之前发送字符串大小。当这样做时,出现字节序 - Java是big-endian,更改是,你的另一边是little-endian。

First problem is that when the string is sent this way, the other fellow has no idea what would be the length of the string! So you need to indicate it, and the common technique is to send string size before the actual string. When doing so, whatch out for endianness - Java is big-endian, and changes are, your other side is little-endian.

第二个问题是,你不能希望通过单个 recv 命令一次接收所有内容。你必须循环接收,直到你已经阅读了所有的东西。

Second problem is that you can't hope to receive everything in one shot through a single recv command. You have to receive in a loop, until you've read all what is there.

这篇关于如何从java服务器发送字符串到C ++客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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