Socket通信-服务端

            WSADATA wsd;
	SOCKET sClient;
	SOCKET sServer;
	SOCKADDR_IN addrServ;
	char chRcvBuf[RECV_BUF_SIZE];

	if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
	{
		Sleep(5000);
		continue;
	}
	sServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (INVALID_SOCKET == sServer)
	{
		WSACleanup();
		Sleep(5000);
		continue;
	}

	addrServ.sin_family = AF_INET;
	addrServ.sin_port = htons(4999);
	addrServ.sin_addr.s_addr = INADDR_ANY;
	int nretVal = bind(sServer, (LPSOCKADDR)&addrServ, sizeof(SOCKADDR_IN));
	if (SOCKET_ERROR == nretVal)
	{
		closesocket(sServer);
		WSACleanup();
		Sleep(5000);
		continue;
	}

	nretVal = listen(sServer, 1);
	if (SOCKET_ERROR == nretVal)
	{
		closesocket(sServer);
		WSACleanup();
		Sleep(5000);
		continue;
	}

	sockaddr_in addrClient;
	int addrClientlen = sizeof(addrClient);
	sClient = accept(sServer, (sockaddr FAR*)&addrClient, &addrClientlen);
	if (INVALID_SOCKET == sClient)
	{
		closesocket(sServer);
		WSACleanup();
		Sleep(5000);
		continue;
	}

	ZeroMemory(chRcvBuf, RECV_BUF_SIZE);
	nretVal = recv(sClient, chRcvBuf, RECV_BUF_SIZE, 0);
	if (SOCKET_ERROR == nretVal)
	{
		closesocket(sServer);
		closesocket(sClient);
		WSACleanup();
		Sleep(5000);
		continue;
	}

	if (strlen(chRcvBuf) > 0 && strlen(chRcvBuf) < RECV_BUF_SIZE)
		ParseCmd(chRcvBuf);

	closesocket(sServer);
	closesocket(sClient);
	WSACleanup();
posted @ 2020-09-22 16:32  Mojito2020  阅读(155)  评论(0编辑  收藏  举报