#include <WinSock2.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
int main()
{
//加载socket动态库
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2,2);
auto err = WSAStartup(wVersionRequested, &wsaData);
if(err != 0)
{
int c = 0;
}
if(LOBYTE(wsaData.wVersion) != 2 ||
HIBYTE(wsaData.wVersion) != 2)
{
int c = 0;
}
SOCKET socketSer = socket(AF_INET, SOCK_STREAM, 0);
//定义成非阻塞
int per = 1;
if(ioctlsocket(socketSer,FIONBIO,(u_long *)&per) != 0)
{
int c = 0;
}
SOCKADDR_IN serverAddr;
memset(&serverAddr,0,sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(22000);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); /*有IP*/
bind(socketSer,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
listen(socketSer,5);
SOCKADDR_IN socketClient;
int socketLength = sizeof(SOCKADDR);
while(true)
{
//非堵塞 立即返回
SOCKET Command_Sock = accept(socketSer, (SOCKADDR*)&socketClient,&socketLength);
if(Command_Sock == INVALID_SOCKET)
{
Sleep(100);
continue;
}
char data[50];
printf("IP:%s",inet_ntoa(socketClient.sin_addr));
//非堵塞 立即返回
recv(Command_Sock,data,sizeof(data),0);
printf("%s\n",data);
closesocket(Command_Sock);
//WSACleanup();
}
WSACleanup();
return 0;
#include <stdio.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
int main()
{
//加载socket动态库
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2,2);
auto err = WSAStartup(wVersionRequested, &wsaData);
if(err != 0)
{
int c = 0;
}
if(LOBYTE(wsaData.wVersion) != 2 ||
HIBYTE(wsaData.wVersion) != 2)
{
int c = 0;
}
SOCKET socketSer = socket(AF_INET, SOCK_STREAM, 0);
//定义成非阻塞
int per = 1;
if(ioctlsocket(socketSer,FIONBIO,(u_long *)&per) != 0)
{
int c = 0;
}
SOCKADDR_IN serverAddr;
memset(&serverAddr,0,sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(22000);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); /*有IP*/
bind(socketSer,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
listen(socketSer,5);
SOCKADDR_IN socketClient;
int socketLength = sizeof(SOCKADDR);
while(true)
{
//非堵塞 立即返回
SOCKET Command_Sock = accept(socketSer, (SOCKADDR*)&socketClient,&socketLength);
if(Command_Sock == INVALID_SOCKET)
{
Sleep(100);
continue;
}
char data[50];
printf("IP:%s",inet_ntoa(socketClient.sin_addr));
//非堵塞 立即返回
recv(Command_Sock,data,sizeof(data),0);
printf("%s\n",data);
closesocket(Command_Sock);
//WSACleanup();
}
WSACleanup();
return 0;
}
或者另一种方式
前面监听什么都一样
//后面就不同
在线程中轮询调用accept 如果有连接再开创一个子线程用于和client端对话,
这种不适合用于有大量client端的架构中,线程量的急剧增加会降低系统的性能