如何为服务器上的每个接受的客户端创建线程? [英] how to create thread for each accepted client on server ?
本文介绍了如何为服务器上的每个接受的客户端创建线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
接受连接的线程中的此函数
this function in thread that accept connection
while(true)
{
s = accept(Socket,(struct sockaddr*)&client,&len);
if( s >-1)
{
re = new HandleResponse();
re->set_Client(s);
//re->Set_client(Socket);
re->start();
re->gt;join();
delete re;
printf("count client");
}
}
和这个
HandleRequest线程
and this
HandleRequest thread
int HandleResponse::Read()
{
int r = read(Socket,bbuf,sizeof(bbuf));
return r;
}
int HandleResponse::Write()
{
int w = write(Socket,bbuf,sizeof(bbuf));
return w;
}
void* HandleResponse::run() // when call start it call this function thread
{
while(true)
{
Read();
Write();
}
return 0;
}
问题它只接受一个客户并回复它但不接受任何其他客户
i认为问题是代码等待re-> join()并停止接受if if accept
problem it only accept one client and respond to it but did't accept any other client
i think the problem is the code wait on re->join() and stop to accept if accept once
推荐答案
你可以在大多数平台上使用pthreads。
http://www.cs.nmsu.edu/ ~jcook / Tools / pthreads / pthreads.html [ ^ ]
在Windows上,您可以使用beginthread()或beginthreadex()。
http://msdn.microsoft.com/en-us/library/kdzttdcb .aspx [ ^ ]
作为创建线程的替代方法,您可以将接受的套接字设置为n on-blocking并使用select()进行读取,写入和错误。
http://unixhelp.ed.ac.uk/CGI/man-cgi?select+2 [ ^ ]
这是一个beginthreadex ()示例:
You can use pthreads on most platforms.
http://www.cs.nmsu.edu/~jcook/Tools/pthreads/pthreads.html[^]
On Windows, you can use beginthread() or beginthreadex().
http://msdn.microsoft.com/en-us/library/kdzttdcb.aspx[^]
As an alternative to creating threads, you can set the accepted socket to non-blocking and use select() for reads, writes, and errors.
http://unixhelp.ed.ac.uk/CGI/man-cgi?select+2[^]
Here's a beginthreadex() example:
s = accept(Socket,(struct sockaddr*)&client,&len);
if( s >-1)
{
re = new HandleResponse();
re->set_Client(s);
HANDLE handle = _beginthreadex(NULL, 8192, worker, re, 0, NULL);
CloseHandle(handle);
}
您的工作线程程序看起来像......
Your worker thread procedure could look like ...
static unsigned __cdecl worker(void *context)
{
HandleResponse re = (HandleResponse *)context;
re->run();
return 0;
}
删除对join()的调用。没有必要。
另外,更改run()函数:
Drop the call to join(). There's no need for it.
Also, change the run() function:
void* HandleResponse::run() // when call start it call this function thread
{
int size = 0;
do
{
size = read(Socket, bbuf, sizeof bbuf);
write(Socket, bbuf, size);
}
while (size >= 0); // stop loop when socket closes.
return 0;
}
如果run()是唯一需要读/写的地方,那么Read和Write函数不是真的很必要。
If run() is the only place that needs read/write, the Read and Write functions aren't really necessary.
这篇关于如何为服务器上的每个接受的客户端创建线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文