C++ Socket服务器简单代码示例
//服务器端
void main()
{
WSADATA wsaData;
int errorCode = WSAStartup(MAKEWORD(1,1),&wsaData);
if (errorCode != 0)
return;
SOCKET acceptSocket = socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addr;
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addr.sin_port = htons(6001); //端口号
errorCode = bind(acceptSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR));
if (errorCode != 0)
return;
errorCode = listen(acceptSocket,5);
if (errorCode != 0)
return;
SOCKADDR_IN sockAddr;
int len = sizeof(SOCKADDR);
char recvBuf[5000] = {0};
char sendBuf[5000] = {0};
while (true)
{
SOCKET clientSocket = accept(acceptSocket,(SOCKADDR*)&sockAddr,&len);
if (clientSocket == INVALID_SOCKET)
{
Sleep(100);
continue;
}
memset(sendBuf,0,5000);
sprintf(sendBuf,"%s is Connected!\r\n",inet_ntoa(sockAddr.sin_addr));
printf(sendBuf);
while(true)
{
memset(recvBuf,0,5000);
memset(sendBuf,0,5000);
int ret = recv(clientSocket,recvBuf, 4999,0);
if (ret < 0)
break;
sprintf(sendBuf,"Hello %s ,message recved!\r\n",inet_ntoa(sockAddr.sin_addr));
printf(sendBuf);
ret = send(clientSocket,sendBuf, strlen(sendBuf),0);
if (ret < 0)
break;
}
memset(sendBuf,0,5000);
sprintf(sendBuf,"%s is Closed!\r\n",inet_ntoa(sockAddr.sin_addr));
printf(sendBuf);
closesocket(clientSocket);
}
closesocket(acceptSocket);
WSACleanup();
}