Reputation: 151
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
Upvotes: 2
Views: 143
Reputation: 11769
std::cin >> m;
Will only read until the first instance of whitespace, or a newline if only one word is written:
input.nextLine()
reads until a newline is entered, and spaces don't terminate. To do the equivalent in C++, you need to use getline(std::cin, m)
like this (Don't forget to include <string>
):
getline(std::cin, input)
Upvotes: 1
Reputation: 75062
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.
Upvotes: 4
Reputation: 118292
string m="";
m
is a class called std::string
.
static_cast<void*>(&m),
&m
is the address of the std::string
structure. It is not the address of the actual string that this class represents. You need to obtain the actual contents of the string class, and write that to the socket:
write(socketfd, m.c_str(), m.length()+1);
This is an over-simplified example, but you can think of a std::string
as a class that looks like this:
class std::string {
char *data;
size_t length;
// ...
};
Writing the physical address of this pointer, and other internal contents of the string class to the socket accomplishes nothing useful. You need to obtain the actual string data.
Upvotes: 4