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 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++ 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++ 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.
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.
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.