コード例 #1
0
ファイル: Server.cpp プロジェクト: cveticmilan/Blok1
DWORD WINAPI ThreadProcessRequest(LPVOID lpParam)
{
	T_ThreadParams params = *(T_ThreadParams*)lpParam;
	T_ProcessArray* processArray = params.processArray;
	CircularBuffer* circularBuffer = params.circularBuffer;
	CircularBuffer* syncBuffer = params.syncBuffer;
	SOCKET acceptedSocket = params.socket;
	bool* working = params.working;
	int serviceId = params.serviceId;

	int iResult;
	bool isSync;
	// Buffer used for storing incoming data
	//char recvbuf[DEFAULT_BUFLEN];
	char* recvbuf = (char*)malloc(DEFAULT_BUFLEN);
	DWORD threadId = GetCurrentThreadId();
	while (*working)
	{
		iResult = Receive(sizeof(int) + sizeof(char), acceptedSocket, recvbuf, working);
		if (iResult == SocketStatus::Shutdown || iResult == SocketStatus::Error || iResult == SocketStatus::Closed)
		{
			break;
		}
		unsigned char action = *(recvbuf + sizeof(int));
		int lengthRestOfMsg = *(int*)(recvbuf)-sizeof(int) - sizeof(char);

		iResult = Receive(lengthRestOfMsg, acceptedSocket, recvbuf + sizeof(int) + sizeof(char), working);
		if (iResult == SocketStatus::Shutdown || iResult == SocketStatus::Error || iResult == SocketStatus::Closed)
		{
			break;
		}

		// Receive data and put it on circular buffer
		isSync = *(bool*)(recvbuf + sizeof(int) + sizeof(char));
		if (isSync)
		{
			syncBuffer->Push(recvbuf);
		}
		else
		{
			circularBuffer->Push(recvbuf);
		}
	}

	// shutdown the connection since we're done
	iResult = shutdown(acceptedSocket, SD_BOTH);
	if (iResult == SOCKET_ERROR)
	{
		printf("[126]shutdown failed with error: %d\n", WSAGetLastError());
	}
	// cleanup
	closesocket(acceptedSocket);
	delete (T_ThreadParams*)lpParam;
	free(recvbuf);

	RemoveFromProcessArray(processArray, serviceId);
	printf("[ThreadProcessRequest %d] Ended gracefully\n", threadId);
	return 0;
}