How to read an input from a client via socket in Linux in C++?
My goal is create an app client server, written in C++. When the server read an input from the client, should process the string and give an output. Basically, I have a simply echo server that send the same message. But if the user types a special string (like "quit"), the program have to do something else. My problem is that this one dont happend, because the comparison between strings is not working... I dunno why! Here a simple code:
while(1) {
int num = recv(client,buffer,BUFSIZE,0);
if (num < 1) break;
send(client, ">> ", 3, 0);
send(client, buffer, num, 0);
char hello[6] ="hello";
if(strcmp(hello,buffer)==0) {
send(client, "hello dude! ", 12, 0);
}
buffer[num] = '\0';
if (buffer[n开发者_开发问答um-1] == '\n')
buffer[num-1] = '\0';
std::cout << buffer;
strcpy(buffer, "");
}
Why the comparison is not working? I have tried many solutions...but all failed :(
Your data in buf
may not be NULL-terminated, because buf
contains random data if not initialized. You only know the content of the first num
bytes. Therefore you also have to check how much data you've received before comparing the strings:
const char hello[6] ="hello";
size_t hello_sz = sizeof hello - 1;
if(num == hello_sz && memcmp(hello, buffer, hello_sz) == 0) { ...
As a side note, this protocol will be fragile unless you delimit your messages, so in the event of fragmented reads (receive "hel" on first read, "lo" on the second) you can tell where one message starts and another one ends.
strcmp requires null terminated strings. The buffer you read to might have non-null characters after the received message.
Either right before the read do:
ZeroMemory(buffer, BUFSIZE); //or your compiler defined equivalent
Or right after the read
buffer[num] = '\0';
This will ensure that there is a terminating null at the end of the received message and the comparison should work.
A string is defined to be an array of char
s upto and including the terminating \0
byte. Initially your buffer
contains arbitrary bytes, and is not even guaranteed to contain a string. You have to set buffer[num] = '\0'
to make it a string.
That of course means that recv
should not read sizeof buffer
bytes but one byte less.
精彩评论