Hello All!
I have a problem and I realy need help! I want to make my simple server recognize commands! The problem is that when I recive data from client I get garbage at the end of the data. For example I connect with telnet to my server and send message:
Server displays them like this:This is the first message
I simply store all the recived data into array buffer and this is the result of:This is the first message öÿ¿ ¨õÿ¿) @ @øÈõÿ¿
I know that recv function returns size of the recived data, so I can make just a loop like this, to filter thous characters out:Code:cout << buffer << endl;
This will display me a data without thous garbage characters, but the problem for server to detect command!Code:for(int q=0; q<recv_data_size; q++){ cout << buffer[q]; }
I have my buffer 100 bytes long, so I clear thous garbage characters like this:
I used recv_data_size-2 so that the code allso would clear \n and \r characters!Code:for(int c=recv_data_size-2; c<array_size; c++){ buffer[c] = '\0'; }
This will clean the garbage out and for example if I will send command from client stop, then my buffer will look like this:
The problem is that this code does't work:[s],[t],[o].[p],[\0],[\0]....
Can you please show me how to make my server recognize commands?Code:if(buffer == "stop"){ cout << "Command executed!\n"; }
Here is the source code. I'm on Linux:
Please help me!!! Thank you!Code:#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <iostream> #define port 1000 #define conn 10 #define buffsize 100 using namespace std; int main(){ int sock_fd, fd; struct sockaddr_in server; struct sockaddr_in client; socklen_t sin_size; char buffer[buffsize]; server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr=INADDR_ANY; if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1){ perror("socket();"); exit(1); } if(bind(sock_fd,(struct sockaddr *)&server,sizeof(struct sockaddr)) == -1){ perror("bind();"); exit(1); } if(listen(sock_fd, conn) == -1){ perror("listen();"); exit(1); } sin_size = sizeof(struct sockaddr_in); while(true){ fd = accept(sock_fd,(struct sockaddr *)&client,&sin_size); while(true){ int data_lenght = recv(fd, buffer, sizeof(buffer), 0); for(int q=data_lenght-2; q<buffsize; q++){ buffer[q] = '\0'; } if(buffer == "command"){ cout << "Command executed successfully!\n"; } } } return 0; }



LinkBack URL
About LinkBacks


