我正在尝试创建一个多客户端服务器,并且我设法保护服务器和单个客户端之间的信息交换,但现在我必须使用线程,以便多个客户端可以同时与服务器连接.
我按照互联网上的说明进行操作,但出现错误
'
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;
}