客户端命令由服务器C处理

时间:2014-03-31 02:02:12

标签: c++ winapi client-server named-pipes

我正在使用命名管道在Win32(C ++)环境中构建服务器/客户端聊天应用程序,我正在努力寻找更好的解决方案来处理客户端请求的命令(而不是并发问题)也不同步)。我能想出的唯一解决方案就是这个:

想象一下,客户端只能向服务器发送一些命令,例如:

-> Logon arg1 arg2
-> Register arg1 arg2
-> Chat_info 
-> Exit

现在,在服务器端,必须处理信息,但他如何捕获参数?

我想要完成的是与服务器的交互而不是来自他的简单回应响应,例如:作为客户端我会发送:Logon Ricardo pass123  并且服务器将检查该用户名和密码是否有效。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

Finnaly我找到了解决问题的更好方法。这是:

Server.c

while(1){
//...
printf("[SERVER] Waiting for a client... (ConnectNamedPipe)\n");
    if(!ConnectNamedPipe(hPipe, NULL)){
        perror("Connection Error!");
        //exit(-1);
    }
    CreateThread(NULL,0,ListenClient,(LPVOID)hPipe,0,NULL);
}

每次客户端创建他的命名管道时,都会获得一个新线程并且在" ListenClient"功能:

DWORD WINAPI ListenClient(LPVOID param) { ... }

将读取通过管道传递的信息,如:

ret = ReadFile(hPipe, buf, 256,(LPDWORD) &n, NULL);
if (!ret || !n)
    perror("Error reading the named pipe!");
buf[n] = '\0'; 

每个客户端可以从服务器请求的选项将具有尽可能多的条件,例如:

if(strcmp(buf, "Logon")==0)
{
 //process the resquest
}


if(strcmp(buf, "Register")==0)
{
 //process the request
}

and so on..

这样服务器将从缓冲区中读取并在发送的第一个参数上进行简单的字符串比较。

谢谢大家,我希望它有所帮助!