简体   繁体   English

如何从java服务器向C ++客户端发送字符串?

[英]How to send a string from java server to C++ client?

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: 我需要从windows java服务器发送一个字符串到linux c ++客户端,反之亦然,但我写的代码不起作用,我不知道原因:

Java server Code on Windows to send a string : Windows上的Java服务器代码发送字符串

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 : Windows上用于接收数据的 Java服务器代码:

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

C++ client code on Linux to send data : Linux上的C ++客户端代码发送数据

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

C++ client code on Linux to receive data : Linux上用于接收数据的 C ++客户端代码:

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. 其中两个,实际上。

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. 当这样做时,对于字节序的问题 - Java是大端的,而变化是,你的另一面是小端。

Second problem is that you can't hope to receive everything in one shot through a single recv command. 第二个问题是你不能希望通过一个recv命令一次性接收所有内容。 You have to receive in a loop, until you've read all what is there. 你必须循环接收,直到你读完所有的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM