我正在尝试创建一个多客户端服务器,并设法确保服务器和单个客户端之间的信息交换, 但现在我必须使用线程,以便多个客户端可以同时与服务器连接。
我按照互联网上的说明操作,但收到错误
'
CreateThread
':无法将参数3从“unsigned long (void *)
”转换为“unsigned long (__stdcall *) (void *)
”
你会看到在这个函数中,我返回0,因为我不知道该返回什么。
这是我的代码:
#include"serveur.h"
server::server(int p)
{
port = p;
}
int server::init()
{
WORD wVersionRequested;
WSADATA Data;
int error= (WSAStartup(MAKEWORD(2,2), &Data ));
if(error != 0 )
{
cerr <<"WSAStartup a échoué "<< endl;
return 1;
}
else
{
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons( port );
ServerAddr.sin_addr.s_addr=htons(INADDR_ANY) ;
}
cout <<"server correctement initialise" << endl;
return 0;
}
DWORD WINAPI server::ClientThread(void * p)
{
struct thread_param *Obj = (struct thread_param *) p ;
server *s = Obj->ser;
cout << "thread client start" << endl;
char buffer[100];
//**** sent ****
strcpy(buffer, "coucou \n");
send(Obj->soc, buffer,strlen(buffer), 0);
cout<<"message envoye"<<endl;
int reponse = 0;
do
{
// cout<<"******** reception ...********"<<endl;
reponse = recv(Obj->soc, buffer, sizeof(buffer), 0);
cout<<"reponse"<<reponse<<endl;
buffer[reponse]='\0';
cout<<"msg recu "<<buffer<<endl;
}while(reponse=0);
return 0;
}
int server::start ()
{
SOCKADDR_IN ClientAddr;
int ClientAddrLen;
HANDLE hProcessThread;
struct thread_param p;
ListeningSocket = socket(AF_INET, SOCK_STREAM, 0);
if(ListeningSocket == INVALID_SOCKET)
{
perror("socket()");
exit(-1);
}
cout <<"socket correctement creee" << endl;
if( bind( ListeningSocket, (SOCKADDR *)&ServerAddr, sizeof( ServerAddr ) ) == SOCKET_ERROR )
{
cerr<<"bind a echoue avec l'erreur "<< WSAGetLastError()<< endl;
cerr<<"Le port est peut-être deja utilise par un autre processus "<< endl;
return 1;
}
cerr<<"Bind... "<< endl;
if( listen( ListeningSocket, 5 ) == SOCKET_ERROR )
{
cerr<<"listen a échoué avec l'erreur "<< WSAGetLastError()<< endl;
return 1;
}
cout <<"serveur demarre : a l ecoute du port "<<port<< endl;
running = true;
ClientAddrLen = sizeof( ClientAddr );
while(running)
{
if(Newconnection = accept(ListeningSocket, (struct sockaddr *)&ClientAddr, &ClientAddrLen) == INVALID_SOCKET)
{
cout<<"accept a echoue avec l erreur "<< WSAGetLastError() << endl;
return 1;
}
p.ser=this;
p.soc=Newconnection;
cout<<"client connecte..."<<endl;
hProcessThread = CreateThread(NULL, 0,ClientThread, &p,0,NULL);
if ( hProcessThread == NULL )
{
cerr <<"CreateThread a échoué avec l'erreur "<<GetLastError()<< endl;
}
}
closesocket( ListeningSocket );
WSACleanup();
return 0;
}
答案 0 :(得分:1)
您将无法将成员函数作为函数指针传递给这样的c风格函数。您可以使用一个静态函数,该函数将指针指向this
,然后转换对象并从静态函数中调用您的成员函数。或者,更好的是,使用std::thread.