#include "stdafx.h"

#include <stdio.h>
#include "winsock2.h"
#include "classdef.h"
#include "constdef.h"
#include <process.h>

#pragma comment (lib, "Ws2_32.lib")

DWORD WINAPI clientThread(LPVOID lparam);

unsigned int __stdcall listeningThread(void *param)
{
	SOCKET local_socket, client_socket;
	sockaddr_in service, client_sock_addr;
	PARA* clientInfo;

	local_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(local_socket == INVALID_SOCKET)
	{
		//printf("socket failed\n");
		exit(0);
	}

	service.sin_family = AF_INET;
	service.sin_addr.S_un.S_addr = INADDR_ANY;
	service.sin_port = htons(int(param));


	if(bind(local_socket, (sockaddr*)&service, sizeof(sockaddr)) == SOCKET_ERROR)
	{
		//printf("bind failed\n");
		exit(0);
	}

	if(listen(local_socket, BACKLOG) == SOCKET_ERROR)
	{
		//printf("listen failed\n");
		exit(0);
	}

	//printf("****************************Web server start up!****************************\n\n");

	while(1)
	{
		int sockaddrLength = sizeof(sockaddr);
		client_socket = accept(local_socket, (sockaddr*)&client_sock_addr, &sockaddrLength);
		if(client_socket == INVALID_SOCKET)
		{
			//printf("accept failed\n");
			continue;
		}

		clientInfo = new PARA;
		clientInfo->s = client_socket;
		memcpy((void*)&(clientInfo->addr), &client_sock_addr, sizeof(client_sock_addr));
		//clientInfo.addr=clientSockaddr;

		clientThread((LPVOID)clientInfo);

		//DWORD lpThreadId;
		//HANDLE hThread;
		//hThread = CreateThread(NULL, 0, clientThread, (LPVOID)clientInfo, 0, &lpThreadId);
		//if(hThread != NULL)
		//{
		//	//printf("------------------Start one connect!------------------\n");
		//}
		//else
		//{
		//	//printf("------------------One client connection failed!\n------------------");
		//}
	}
	//closesocket(local_socket);
	//WSACleanup();
}

//void main()
//{
//	WORD wVersionRequested;
//	WSADATA wsaData;
//	int err;
//	wVersionRequested = MAKEWORD(2, 2);
//	err = WSAStartup(wVersionRequested, &wsaData);
//	if (err != 0) {
//		return;
//	}
//
//	_beginthreadex(NULL, 0, listeningThread, (void *) 8120, 0, NULL);
//	_beginthreadex(NULL, 0, listeningThread, (void *) 8121, 0, NULL);
//	Sleep(INFINITE);
//}