开发平台(Platform): (Ex: Win10, Linux, ...)
Mac OS Mojave
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
G++
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
问题(Question):
我做了一个server想接收client的指令去执行,但是我将指令传到
server时,server无法判断指令,所以我先做了一个小程式,把收到的指令印出来,
并判断他是不是ls,结果还是不行
喂入的资料(Input):
ls
预期的正确结果(Expected Output):
印出recevied:'ls'
yes
错误结果(Wrong Output):
server:
client connected with ip address: 0.0.0.0
received: 'ls
'
received: 'ls
'
client:
telnet 0.0.0.0 8877
Trying 0.0.0.0...
Connected to 0.0.0.0.
Escape character is '^]'.
ls
ls
程式码(Code):(请善用置底文网页, 记得排版,禁止使用图档)
int main(int argc, char *argv[]) {
int SERVER_PORT = 8877;
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(SERVER_PORT);
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
int listen_sock;
if ((listen_sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
printf("could not create listen socket\n");
return 1;
}
if ((bind(listen_sock, (struct sockaddr *)&server_address,sizeof(server_address))) < 0) {
printf("could not bind socket\n");
return 1;
}
int wait_size = 16; // maximum number of waiting clients, after which
// dropping begins
if (listen(listen_sock, wait_size) < 0) {
printf("could not open socket for listening\n");
return 1;
}
struct sockaddr_in client_address;
socklen_t client_address_len = 0;
while (true) {
int sock;
if ((sock =accept(listen_sock, (struct sockaddr *)&client_address, &client_address_len)) < 0) {
printf("could not open a socket to accept data\n");
return 1;
}
int n = 0;
int len = 0, maxlen = 100;
char buffer[maxlen];
char *pbuffer = buffer;
printf("client connected with ip address: %s\n",inet_ntoa(client_address.sin_addr));
while ((n = recv(sock, pbuffer, maxlen, 0)) > 0) {
pbuffer += n;
maxlen -= n;
len += n;
printf("received: '%s'\n", buffer);
string line=buffer;
line=line.substr(0,n);
printf("received: '%s'\n", line.c_str());
if (!strcmp(buffer,"ls")){
printf("yes");
}
if (line=="ls"){
printf("yes");
}
send(sock, buffer, len, 0);
}
close(sock);
}
close(listen_sock);
return 0;
}
补充说明(Supplement):
看起来传回去的东西是没问题的,但是为什么我server收到的东西不太对。
1.右括号被换行了
2.没有判断出我传的是ls(应该要印出yes)
请各位大大救救我QQ
感谢!