所以,我正在编写一个小的winsock应用程序,我需要创建一个多客户端服务器。 我决定为每个新连接使用线程,问题是我不知道如何将多个数据传递给线程,所以我使用struct。
STRUCT:
typedef struct s_par {
char lttr;
SOCKET clientSocket;
} par;
_stdcall:
unsigned __stdcall ClientSession(void *data) {
par param = data;
char ch = param.lttr;
SOCKET clntSocket = param.clientSocket;
// ..working with client
}
主:
int main() {
unsigned seed = time (0);
srand(seed);
/*
..........
*/
SOCKET clientSockets[nMaxClients-1];
char ch = 'a' + rand()%26;
while(true) {
cout << "Waiting for clients(MAX " << nMaxClients << "." << endl;
while ((clientSockets[nClient] = accept(soketas, NULL, NULL))&&(nClient < nMaxClients)) {
par param;
// Create a new thread for the accepted client (also pass the accepted client socket).
if(clientSockets[nClient] == INVALID_SOCKET) {
cout << "bla bla" << endl;
exit(1);
}
cout << "Succesfull connection." << endl;
param.clientSocket = clientSockets[nClient];
param.lttr = ch;
unsigned threadID;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ClientSession, ¶m, 0, &threadID);
nClient++;
}
问题是我在数据类型转换时遇到错误。也许有人可以通过将这个结构传递给一个线程来建议一个简单的解决方法吗?
答案 0 :(得分:3)
在while
循环的每一轮中,你都会做两个不明智的活动:
HANDLE
_beginthreadex
这些都不好。理想情况下,你的线程proc应该是这样的:
unsigned __stdcall ClientSession(void *data)
{
par * param = reinterpret_cast<par*>(data);
char ch = param->lttr;
SOCKET clntSocket = param->clientSocket;
// ..working with client
delete param;
return 0U;
}
呼叫方也应该这样做:
par *param = new par;
param->clientSocket = clientSockets[nClient];
param->lttr = ch;
...
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ClientSession, param, 0, &threadID);
if (hThread != NULL)
CloseHandle(hThread);
else
delete param; // probably report error here as well
这应该足以让你前进。我建议你不妨花一些时间来了解C++11 Threading Model。它使大部分内容更加优雅(便携!)。
祝你好运。