vc++ 多线程编程 SOCKET通信 20
#include<iostream>#include<winsock2.h>#pragmacomment(lib,"ws2_32.lib")usingnamespaces...
#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
#include <process.h>
DWORD WINAPI ThreadFunc(LPVOID n)
{
SOCKET ssock;
ssock=(SOCKET)(LPVOID)n;
char buf[1000];
while(1){
recv(ssock,buf,1000,0);
if(buf==("exit"+'\0'))
break;
else
cout<<buf<<endl;
}
return 0;
}
int main(){
SOCKET sock;
sockaddr_in serveraddr;
WSADATA wsaData;
WSAStartup(0x202,&wsaData);
sock = socket(AF_INET, SOCK_STREAM, 0 );
memset((void *)&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(8888);
bind(sock,(sockaddr *)&serveraddr, sizeof(serveraddr));
listen(sock,SOMAXCONN);
while(1)
{
SOCKET ssock;
ssock=SOCKET_ERROR;
while(ssock==SOCKET_ERROR)
{
ssock=accept(sock,NULL,NULL);
}
printf("Client Connected.\n");
DWORD dwThreadId;
HANDLE hThread;
hThread=CreateThread(NULL,NULL,ThreadFunc,
(LPVOID)ssock,0,&dwThreadId);
CloseHandle(hThread);
Sleep(400000);
closesocket(ssock);
}
WSACleanup();
system("pause");
return 0;
}
服务端主程序如上,为何只能同时接受一个用户的连接,而不能同时接受多个用户的连接 展开
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
#include <process.h>
DWORD WINAPI ThreadFunc(LPVOID n)
{
SOCKET ssock;
ssock=(SOCKET)(LPVOID)n;
char buf[1000];
while(1){
recv(ssock,buf,1000,0);
if(buf==("exit"+'\0'))
break;
else
cout<<buf<<endl;
}
return 0;
}
int main(){
SOCKET sock;
sockaddr_in serveraddr;
WSADATA wsaData;
WSAStartup(0x202,&wsaData);
sock = socket(AF_INET, SOCK_STREAM, 0 );
memset((void *)&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(8888);
bind(sock,(sockaddr *)&serveraddr, sizeof(serveraddr));
listen(sock,SOMAXCONN);
while(1)
{
SOCKET ssock;
ssock=SOCKET_ERROR;
while(ssock==SOCKET_ERROR)
{
ssock=accept(sock,NULL,NULL);
}
printf("Client Connected.\n");
DWORD dwThreadId;
HANDLE hThread;
hThread=CreateThread(NULL,NULL,ThreadFunc,
(LPVOID)ssock,0,&dwThreadId);
CloseHandle(hThread);
Sleep(400000);
closesocket(ssock);
}
WSACleanup();
system("pause");
return 0;
}
服务端主程序如上,为何只能同时接受一个用户的连接,而不能同时接受多个用户的连接 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询