Ido Ikar Ido Ikar - 2 months ago 7
Java Question

socket between c++ and java

I wrote a server in c++ and to send messages I set the follow thread:

void *send(void* v)
{
string m="";
while(true)
{
std::cin >> m;
write(socketfd, static_cast<void*>(&m), m.length()+1);
}
}


to read the messages I wrote the follwing code:

public void recieve() throws IOException{
while (true){
if(input.hasNext()){
viewText.setText(viewText.getText() + "\nSever: "+input.nextLine());
}
}
}

@Override
public void run() {
try {
recieve();
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


When I write into the variable M and press enter, nothing happen. But when I close the server, all the values of m i wrote before are printed as one string.

I Apologize for the incorrect English.
tnks

Answer

Not knowing the type of input in your Java code, the method name nextLine() suggests that it will read a whole line. Line is sequence of characters which is terminated with newline character. On the other hand, no newline character will be stored via std::cin >> m;, so all data until terminating the sending side will be treated as one line.

To send multiple lines, you should use another way such as std::getline(std::cin, m); to read input and add newline characters if the way drops them.

Comments