在c++windows中进行客户端-服务器程序设计的多线程
Multithread in client server programming in c++ windows
我有一个问题,如何同时向客户端发送字符串。我的程序将客户端放在一个队列中,所以当第一个客户端断开连接时,第二个客户端连接,我真的想把它们放在多线程中,但我不知道怎么做,任何人都请帮助我,谢谢。
void abc(CSocket sockClients[],int i)
{
int MsgSize;
char *temp;
// Nhan username tu Server
sockClients[i].Receive((char*)&MsgSize,sizeof(int),0); // Neu nhan loi thi tra ve la SOCKET_ERROR.
temp = new char[MsgSize +1];
sockClients[i].Receive((char*)temp,MsgSize,0);
// In username ra
temp[MsgSize] =' ';
int score=3;
int ques;
sockClients[i].Receive((char*)&ques,sizeof(int),0);
ifstream CH;
CH.open("cauhoi.txt",ios::in);
ifstream DA;
DA.open("dapan.txt",ios::in);
for(int j=0;j<ques;j++)
{
char* CH_SV=new char;
CH>>CH_SV;
int Size = strlen(CH_SV);
sockClients[i].Send(&Size,sizeof(int),0);
sockClients[i].Send(CH_SV,Size,0);
char* DA_SV=new char;
DA>>DA_SV;
char *dapan;
sockClients[i].Receive((char*)&Size,sizeof(int),0);
dapan = new char[Size +1];
sockClients[i].Receive((char*)dapan,Size,0);
dapan[Size] =' ';
cout<<"nDap an la: "<<dapan<<endl;
if(Size<5)
goto Exit;
else if(strcmp(dapan,DA_SV)==0)
score+=2;
else score--;
}
sockClients[i].Close();
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
// initialize MFC and print and error on failure
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failedn"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
CSocket server;
AfxSocketInit(NULL);
server.Create(3456);
server.Listen();
int nclient;
cout<<"Nhap so luong client: ";
cin>>nclient;
CSocket * sockClients = new CSocket[nclient];
for (int i = 0; i <nclient; i++)
{
server.Accept(sockClients[i]);
printf("nClient: %d/%d",i+1,nclient);
sockClients[i].Send((char*)&i,sizeof(int),0);
abc(sockClients,i);
}
server.Close();
}
}
else
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: GetModuleHandle failedn"));
nRetCode = 1;
}
return nRetCode;
}
在MSDN中搜索"CSocket+thread",您会发现以下示例:
http://support.microsoft.com/kb/175668/en-us
相关文章:
- 桌面计算器出现问题.C++程序设计语言
- C++服务器程序循环打印
- UDP客户端/服务器程序在不同的IP和端口上通信超过2个插座
- 绑定 API 在服务器程序中究竟做了什么
- C++Qt程序设计问题
- TCP 客户端服务器程序
- 如何避免在C 11服务器程序中为多个客户端使用多个线程
- 嵌入式设备中传感器应用程序设计体系结构
- 关于多态性和资源管理的程序设计
- 客户端无法连接到LAN中的服务器程序
- 视图状态和应用程序设计
- 套接字 TCP 服务器程序问题
- C++面向对象的客户端套接字应用程序设计
- 程序设计方法
- UDP客户端-服务器程序使用gcc而不是g++进行编译
- 关于异常规范和应用程序设计的问题
- 为什么我的程序设计为用完 RAM 和 CPU 不使用所有 RAM 和 CPU?
- 具有多态性和不同数据结构的程序设计
- C ++中的简单客户端服务器程序不起作用
- 在c++windows中进行客户端-服务器程序设计的多线程