Ejemplo n.º 1
0
void CClientReceiver::SetClosed(void)
{
	if( m_pCriticalSection != NULL && m_pThreadData != NULL )
	{
		CSingleLock singleLock( m_pCriticalSection, true );

		*(m_pThreadData->m_peStatus) = ListeningSocket::CLOSED;

		WSASetEvent( m_pThreadData->m_aReservedEvents[1] );
	}
}
Ejemplo n.º 2
0
static
BOOL
on_console_ctrl (
	DWORD		dwCtrlType
	)
{
	printf ("on_console_ctrl (dwCtrlType:%lu)\n", (unsigned long)dwCtrlType);
	is_terminated = TRUE;
	WSASetEvent (terminateEvent);
	return TRUE;
}
Ejemplo n.º 3
0
FTConnectionModule::~FTConnectionModule()
{
	// Kill the thread
	if(p_critical_section!=NULL)
	{
		WSASetEvent(p_thread_data->m_reserved_events[0]);
	}

	// Destroy message window
	m_wnd.DestroyWindow();
}
Ejemplo n.º 4
0
/**
 * lws_cancel_service() - Cancel servicing of pending websocket activity
 * @context:	Websocket context
 *
 *	This function let a call to lws_service() waiting for a timeout
 *	immediately return.
 */
LWS_VISIBLE void
lws_cancel_service(struct lws_context *context)
{
	struct lws_context_per_thread *pt = &context->pt[0];
	int n = context->count_threads;

	while (n--) {
		WSASetEvent(pt->events[0]);
		pt++;
	}
}
Ejemplo n.º 5
0
void NET_Thread::Stop()
{
	LOG_V0_AddMessage(LOG_V0_DEBUG_MESSAGE, m_socket->GetName() + " " + GetName() + "::Stop() started");
	if (!m_executing)
	{
		LOG_V0_AddMessage(LOG_V0_DEBUG_MESSAGE, m_socket->GetName() + " " + GetName() + "::Stop() finished (was not executing)");
		return;
	}
	BeforeStop();
	WSASetEvent(m_events[0]); 
	WaitForSingleObject(m_thread_stopped_event, INFINITE);
	LOG_V0_AddMessage(LOG_V0_DEBUG_MESSAGE, m_socket->GetName() + " " + GetName() + "::Stop() finished");
}
//
// Function: AssignToFreeThread
//
// Description:
//    This routine assigns a socket connection to an available child
//    thread to handle any IO on it. If no threads are available, a 
//    new thread is spawned to handle the connection.
//
void AssignToFreeThread(SOCKET_OBJ *sock)
{
    THREAD_OBJ *thread=NULL;

    thread = gChildThreads;
    while (thread)
    {
        // If this routine returns something other than SOCKET_ERROR
        //    that it was successfully assigned to a child thread.
        if (InsertSocketObj(thread, sock) != SOCKET_ERROR)
            break;
        thread = thread->next;
    }

    if (thread == NULL)
    {
        // No thread was found to assign the client socket to, create a new thread
        //
        printf("Creating new thread object\n");

        thread = GetThreadObj();

        thread->Thread = CreateThread(NULL, 0, ChildThread, (LPVOID)thread, 0, NULL);
        if (thread->Thread == NULL)
        {
            fprintf(stderr, "AssignToFreeThread: CreateThread failed: %d\n", GetLastError());
            ExitProcess(-1);
        }

        InsertSocketObj(thread, sock);

        // Insert the thread the list of threads
        if (gChildThreads == NULL)
        {
            gChildThreads = thread;
        }
        else
        {
            thread->next = gChildThreads;
            gChildThreads = thread;
        }

        gChildThreadsCount++;

    }
 
    // signal child thread to rebuild the event list
    WSASetEvent(thread->Event);

    return;
}
Ejemplo n.º 7
0
void NET_Client::StopConnect(bool asyncro)
{
	LOG_V0_AddMessage(LOG_V0_DEBUG_MESSAGE, GetName() + (TXT("::StopConnect(%s)") << (asyncro?"async":"sync")));

//	MutexWrap socket_access(m_socket_mutex);
	if (!m_created/* || (!m_connecting && !m_connected)*/)
		return;

	if (asyncro)
	{
		WSASetEvent(m_wait_thread.Event(WT_STOP_CONNECT));
	}
	else
		PrivateStopConnect();
}
Ejemplo n.º 8
0
Archivo: Os.c Proyecto: broonie/ohNet
int32_t OsNetworkInterrupt(THandle aHandle, int32_t aInterrupt)
{
    int32_t err = 0;
    OsNetworkHandle* handle = (OsNetworkHandle*)aHandle;
    OsMutexLock(handle->iCtx->iMutex);
    handle->iInterrupted = aInterrupt;
    if (aInterrupt != 0) {
        (void)WSASetEvent(handle->iEvent);
    }
    else {
        (void)WSAResetEvent(handle->iEvent);
    }
    OsMutexUnlock(handle->iCtx->iMutex);
    return err;
}
Ejemplo n.º 9
0
void CTcpIocpServer::Destroy(void)
{
	// 销毁SOCKET套接字
	if(INVALID_SOCKET != m_hListenSocket)
	{
		DestroySocket(m_hListenSocket);
		m_hListenSocket = INVALID_SOCKET;
	}

	//关闭检查线程
	if(INVALID_HANDLE_VALUE != m_hAcceptEvent)
	{
		WSASetEvent(m_hAcceptEvent);
	}

	//等待Context删除完成
	while ((GetTcpContextCount() > 0 || GetAcceptExCount() > 0))
	{
		//关闭所有已连接SOCKET
		CloseAllContext();

		//关闭所有未连接SOCKET
		CloseAllAcceptExSocket();

		Sleep(5);
	}

	// 销毁完成端口句柄
	if(INVALID_HANDLE_VALUE != m_hIocp)
	{
		DestroyCompletePort(m_hIocp);
		m_hIocp = INVALID_HANDLE_VALUE;
	}

	// 销毁ACCEPT事件
	if(INVALID_HANDLE_VALUE != m_hAcceptEvent)
	{
		DestroyAcceptEvent(m_hAcceptEvent);
		m_hAcceptEvent = INVALID_HANDLE_VALUE;
	}

	// 等待线程退出
	m_CheckThread.WaitThreadExit();

	// 清空缓存
	m_OverloapCache.Clear();
}
Ejemplo n.º 10
0
void ConnectionModule::PerformProjectSupplyQuery(ProjectSupplyQuery &psq)
{
	if(p_critical_section==NULL)
	{
		return;
	}

	// Tell the thread to connect to these hosts
	CSingleLock singleLock(p_critical_section);
	singleLock.Lock();
	if(singleLock.IsLocked())
	{
		p_thread_data->p_project_supply_queries->push_back(psq);
		WSASetEvent(p_thread_data->m_reserved_events[1]);	// vector data
		singleLock.Unlock();
	}
}
Ejemplo n.º 11
0
/*=== stop all threads */
int tnet_transport_stop(tnet_transport_t *transport)
{
    int ret;

    if ((ret = tsk_runnable_stop(TSK_RUNNABLE(transport)))) {
        return ret;
    }

    if (transport->mainThreadId[0]) {
        WSASetEvent(((transport_context_t*)(transport->context))->events[0]);
        return tsk_thread_join(transport->mainThreadId);
    }
    else {
        /* already stoppped */
        return 0;
    }
}
Ejemplo n.º 12
0
/**
 * Service control handler. Called by serviceControlManager when a control
 * code is sent to the service (with ControlService).
 * @param ctrl: control code
 */
static void 
hdlr(DWORD ctrl)
{
	if(ctrl == SERVICE_CONTROL_STOP) {
		report_status(SERVICE_STOP_PENDING, NO_ERROR, 0);
		service_stop_shutdown = 1;
		/* send signal to stop */
		if(!WSASetEvent(service_stop_event))
			log_err("Could not WSASetEvent: %s",
				wsa_strerror(WSAGetLastError()));
		return;
	} else {
		/* ctrl == SERVICE_CONTROL_INTERROGATE or whatever */
		/* update status */
		report_status(service_status.dwCurrentState, NO_ERROR, 0);
	}
}
Ejemplo n.º 13
0
void NET_WaitThread::OnEvent(DWORD event_num)
{
	WSANETWORKEVENTS wsa_events;
	CString log;
	switch(event_num)
	{
		case WT_CONNECTED:
			WSAEnumNetworkEvents(m_socket->GetSocket(), Event(WT_CONNECTED), &wsa_events);
			if ((wsa_events.lNetworkEvents & FD_CONNECT) == 0 || wsa_events.iErrorCode[FD_CONNECT_BIT] != 0)
			{
				if (wsa_events.iErrorCode[FD_CONNECT_BIT] == 0)
				{
					CString err;
					err.Format("NET_WaitThread::OnEvent, WT_CONNECTED error_code = %d", wsa_events.iErrorCode[FD_CONNECT_BIT]);
					m_socket->OnError(err);
				}
				break;
			}
			m_socket->SelectEvent(Event(WT_CONNECTED), 0);
			((NET_Client*)m_socket)->PrivateOnConnected();
			break;
		case WT_ACCEPTED:
			((NET_Server*)m_socket)->PrivateOnConnectionAccepted();
			break;
		case WT_STOP_CONNECT:
			m_socket->SelectEvent(m_socket->m_read_thread.Event(0), 0);
			AfxBeginThread(TerminationThreadProcedure, m_socket, THREAD_PRIORITY_LOWEST);
			break;
		case WT_START_CONNECT:
			if (NET_shutdown)
			{
				LOG_V0_AddMessage(LOG_V0_DEBUG_MESSAGE, "Trying to Connect!!!");
				return;
			}
			if (!((NET_Client*)m_socket)->PrivateConnect())
			{
				Sleep(200);
				if (!NET_shutdown)
					WSASetEvent(Event(WT_START_CONNECT));
			}
			break;
		default:
			CRUSH("wrong event_num in NET_WaitThread::OnEvent");
	}
}
Ejemplo n.º 14
0
ConnectionModule::~ConnectionModule()
{
	// Kill the thread
	if(p_critical_section!=NULL)
	{
		WSASetEvent(p_thread_data->m_reserved_events[0]);
	}
	if(m_thread!=NULL)
	{
		if(WaitForSingleObject(m_thread->m_hThread,INFINITE)!=WAIT_OBJECT_0)
		{
			//ASSERT(0);
		}
	}
	// Destroy message window
	m_wnd.DestroyWindow();

}
Ejemplo n.º 15
0
void ConnectionModule::ReConnectAll()
{
	if(p_critical_section==NULL)
	{
		return;
	}

    v_connected_host_ips.clear();
	v_connect_to_ips.clear();
	// Tell the thread to reconnect to supernodes
	CSingleLock singleLock(p_critical_section);
	singleLock.Lock();
	if(singleLock.IsLocked())
	{
		p_thread_data->m_reconnect_to_hosts = true;
		WSASetEvent(p_thread_data->m_reserved_events[1]);	// vector data
		singleLock.Unlock();
	}
}
Ejemplo n.º 16
0
Archivo: Os.c Proyecto: tata-/ohNet-1
void OsDestroy()
{
    (void)SymCleanup(gDebugSymbolHandle);
    if (NULL != gInterfaceChangeObserver) {
        gInterfaceChangeObserver->iShutdown = 1;
        (void)WSASetEvent(gInterfaceChangeObserver->iShutdownEvent);
        (void)WaitForSingleObject(gInterfaceChangeObserver->iSem, INFINITE);
        CloseHandle(gInterfaceChangeObserver->iSem);
        WSACloseEvent(gInterfaceChangeObserver->iEvent);
        WSACloseEvent(gInterfaceChangeObserver->iShutdownEvent);
        (void)closesocket(gInterfaceChangeObserver->iSocket);
        free(gInterfaceChangeObserver);
        gInterfaceChangeObserver = NULL;
    }
    (void)WSACleanup();
    OsMutexDestroy(gMutex);
    gMutex = kHandleNull;
    TlsFree(gTlsIndex);
}
Ejemplo n.º 17
0
void CClientReceiver::Stop(void)
{
	// Kill the thread
	if( m_pCriticalSection != NULL )
	{
		WSASetEvent( m_pThreadData->m_aReservedEvents[0] );
		m_pCriticalSection = NULL;
	}

	// Wait for the thread to die
	if( m_pThread != NULL )
	{
		WaitForSingleObject( m_pThread->m_hThread, 5000 );
		m_pThread = NULL;
	}

	// Destroy message window
	this->DestroyWindow();
}
Ejemplo n.º 18
0
/** wait for cron process to finish */
static void
waitforit(PROCESS_INFORMATION* pinfo)
{
	DWORD ret = WaitForSingleObject(pinfo->hProcess, INFINITE);
	verbose(VERB_ALGO, "cronaction done");
	if(ret != WAIT_OBJECT_0) {
		return; /* did not end successfully */
	}
	if(!GetExitCodeProcess(pinfo->hProcess, &ret)) {
		log_err("GetExitCodeProcess failed");
		return;
	}
	verbose(VERB_ALGO, "exit code is %d", (int)ret);
	if(ret != 1) {
		if(!WSASetEvent(service_stop_event))
			log_err("Could not WSASetEvent: %s",
			wsa_strerror(WSAGetLastError()));
	}
}
Ejemplo n.º 19
0
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION:	AcceptThread
--
-- DATE:		Febuary 6th, 2016
--
-- REVISIONS:
--
-- DESIGNER:	Ruoqi Jia
--
-- PROGRAMMER:	Ruoqi Jia
--
-- INTERFACE:	DWORD WINAPI AcceptThread(LPVOID lpParameter)
--					LPVOID lpParamter : Pointer to the void listening socket.
--
-- RETURNS: exit code
--
-- NOTES: Thread created for TCP to accept client. Since this is a blocking call its better to place it in a thread.
--------------------------------------------------------------------------------------------------------------------*/
DWORD WINAPI AcceptThread(LPVOID lpParameter)
{

	AppendToStatus(hStatus, "Accepting connections...\n");

	/* Waits for connection */
	AcceptSocket = accept(SOCKET(lpParameter), NULL, NULL);

	AppendToStatus(hStatus, "Connection Accepted!\n");

	/* Signal the event, which is being blocked in ServerThread */
	if (WSASetEvent(AcceptEvent) == FALSE)
	{
		sprintf(StrBuff, "WSASetEvent() failed with error %d\n", WSAGetLastError());
		AppendToStatus(hStatus, StrBuff);
		return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 20
0
/*
* Add new socket to the watcher.
*/
int tnet_transport_add_socket(const tnet_transport_handle_t *handle, tnet_fd_t fd, tnet_socket_type_t type, tsk_bool_t take_ownership, tsk_bool_t isClient, tnet_tls_socket_handle_t* tlsHandle)
{
    tnet_transport_t *transport = (tnet_transport_t*)handle;
    transport_context_t* context;
    int ret = -1;

    if (!transport) {
        TSK_DEBUG_ERROR("Invalid server handle.");
        return ret;
    }

    if (!(context = (transport_context_t*)transport->context)) {
        TSK_DEBUG_ERROR("Invalid context.");
        return -2;
    }

    if (TNET_SOCKET_TYPE_IS_TLS(type) || TNET_SOCKET_TYPE_IS_WSS(type)) {
        transport->tls.enabled = tsk_true;
    }

    addSocket(fd, type, transport, take_ownership, isClient, tlsHandle);

    if (WSAEventSelect(fd, context->events[context->count - 1], FD_ALL_EVENTS) == SOCKET_ERROR) {
        removeSocket((int)(context->count - 1), context);
        TNET_PRINT_LAST_ERROR("WSAEventSelect have failed.");
        return -1;
    }

    /* Signal if transport is running */
    if (TSK_RUNNABLE(transport)->running || TSK_RUNNABLE(transport)->started) {
        if (WSASetEvent(context->events[0])) {
            TSK_DEBUG_INFO("New socket added to the network transport.");
            return 0;
        }
        TSK_DEBUG_ERROR("Transport not started yet");
        return -1;
    }

    TSK_DEBUG_INFO("Adding socket delayed");
    return 0;
}
Ejemplo n.º 21
0
void NET_Client::StartConnect(CString to_host, WORD to_port)
{
	LOG_V0_AddMessage(LOG_V0_DEBUG_MESSAGE, GetName() + (TXT("::StartConnect(%s, %d)") << to_host << to_port));

	if (m_connecting || m_connected)
		PrivateStopConnect();

	if (!m_created)
		Create();

	m_connecting = true;
	m_to_host = to_host;
	m_to_port = to_port;
	if (!CalculateSocketAddress())
	{
		m_connecting = false;
		return;
	}
	SelectEvent(m_wait_thread.Event(WT_CONNECTED), FD_CONNECT);
	WSASetEvent(m_wait_thread.Event(WT_START_CONNECT));
}
Ejemplo n.º 22
0
void NET_BaseSocket::PrivateOnReceived()
{
	if (!m_created)
		return;
	DWORD to_read, received = 0, flags = 0, space;
	OP( ioctlsocket(m_socket, FIONREAD, &to_read), "NET_BaseSocket::PrivateOnReceived, ioctlsocket" );
	bool repeat = to_read > m_in_buf_size;
	if (repeat)
		to_read = m_in_buf_size;
	m_in_wsa_buf.buf = m_in_buf;
	m_in_wsa_buf.len = to_read;
	m_last_error = 0;
	OP2( WSARecv(m_socket, &m_in_wsa_buf, 1, &received, &flags, m_read_thread.GetOverlapped(), NULL), m_last_error != WSA_IO_PENDING, "NET_BaseSocket::PrivateOnReceived, WSARecv" );
	if (m_last_error == WSA_IO_PENDING)
	{
		LOG_V0_AddMessage(LOG_V0_DEBUG_MESSAGE, TXT("%s::PrivateOnReceived -- PENDING") << GetName());
		WSAResetEvent(m_read_thread.GetOverlapped()->hEvent);
		return;
	}
	{
		MutexWrap in_write_access(m_in_data->m_w_mutex);
		{
			MutexWrap in_read_access(m_in_data->m_r_mutex);
			space = m_in_data->SpaceFor(RingBuffer_WRITE);
		}
		if (space < received)
			OnError("NET_BaseSocket::PrivateOnReceived -- space < received !!!");
		else
		{
			LOG_V0_AddMessage(LOG_V0_DEBUG_MESSAGE, TXT("%s -- получено %d") << GetName() << received);
			m_in_data->Write(m_in_buf, received);
		}
	}

	OnReceived();
	if (repeat || received < to_read)
		WSASetEvent(m_read_thread.Event(0));
}
Ejemplo n.º 23
0
Archivo: Os.c Proyecto: sewood/ohNet
void OsDestroy(OsContext* aContext)
{
    if (aContext == NULL) {
        return;
    }
    (void)SymCleanup(aContext->iDebugSymbolHandle);
    if (NULL != aContext->iInterfaceChangeObserver) {
        aContext->iInterfaceChangeObserver->iShutdown = 1;
        (void)WSASetEvent(aContext->iInterfaceChangeObserver->iShutdownEvent);
        (void)WaitForSingleObject(aContext->iInterfaceChangeObserver->iSem, INFINITE);
        CloseHandle(aContext->iInterfaceChangeObserver->iSem);
        WSACloseEvent(aContext->iInterfaceChangeObserver->iEvent);
        WSACloseEvent(aContext->iInterfaceChangeObserver->iShutdownEvent);
        (void)closesocket(aContext->iInterfaceChangeObserver->iSocket);
        free(aContext->iInterfaceChangeObserver);
        aContext->iInterfaceChangeObserver = NULL;
    }
    (void)WSACleanup();
    OsMutexDestroy(aContext->iMutex);
    aContext->iMutex = kHandleNull;
    TlsFree(aContext->iTlsIndex);
    free(aContext);
}
Ejemplo n.º 24
0
/* 
* Add new socket to the watcher.
*/
int tnet_transport_add_socket(const tnet_transport_handle_t *handle, tnet_fd_t fd, tnet_socket_type_t type, tsk_bool_t take_ownership, tsk_bool_t isClient)
{
	tnet_transport_t *transport = (tnet_transport_t*)handle;
	transport_context_t* context;
	int ret = -1;

	if(!transport){
		TSK_DEBUG_ERROR("Invalid server handle.");
		return ret;
	}

	if(!(context = (transport_context_t*)transport->context)){
		TSK_DEBUG_ERROR("Invalid context.");
		return -2;
	}

	if(TNET_SOCKET_TYPE_IS_TLS(type)){
		transport->tls.have_tls = 1;
	}

	addSocket(fd, type, transport, take_ownership, isClient);
	if(WSAEventSelect(fd, context->events[context->count - 1], FD_ALL_EVENTS) == SOCKET_ERROR){
		removeSocket((context->count - 1), context);
		TNET_PRINT_LAST_ERROR("WSAEventSelect have failed.");
		return -1;
	}

	/* Signal */
	if(WSASetEvent(context->events[0])){
		TSK_DEBUG_INFO("New socket added to the network transport.");
		return 0;
	}

	// ...
	
	return -1;
}
Ejemplo n.º 25
0
BOOL CxServerSocketTCP::StopServer()
{
	if ( m_ThreadContext.hThread != NULL )
	{
		WSASetEvent( m_hCleanupEvent );
		if ( WAIT_OBJECT_0 != ::WaitForSingleObject( m_ThreadContext.hThread, 3000 ) )
		{
			::TerminateThread( m_ThreadContext.hThread, 0 );
		}
		::CloseHandle( m_ThreadContext.hThread );
		m_ThreadContext.hThread = NULL;
	}

	if ( m_hCleanupEvent != WSA_INVALID_EVENT )
		::WSACloseEvent( m_hCleanupEvent );
	m_hCleanupEvent = WSA_INVALID_EVENT;

	if ( m_ThreadContext.hNetEvent[1] != WSA_INVALID_EVENT )
		WSACloseEvent( m_ThreadContext.hNetEvent[1] );
	m_ThreadContext.hNetEvent[1] = WSA_INVALID_EVENT;

	if ( m_ThreadContext.hSocket != INVALID_SOCKET )
	{
		char szBye[3] = { 0, };
		send( m_ThreadContext.hSocket, szBye, 3, 0 );
		shutdown( m_ThreadContext.hSocket, SD_BOTH );
		closesocket( m_ThreadContext.hSocket );
		m_ThreadContext.hSocket = INVALID_SOCKET;
	}

	m_bStarted = FALSE;

	OnStopServer();

	return TRUE;
}
Ejemplo n.º 26
0
void ConnectionModule::ConnectToHosts(vector<SupernodeHost> &hosts)
{
	
	if(p_critical_section==NULL)
	{
		return;
	}

	int i;

	// Tell the thread to connect to these hosts
	CSingleLock singleLock(p_critical_section);
	singleLock.Lock();
	if(singleLock.IsLocked())
	{
		*p_thread_data->p_connect_hosts=hosts;
		WSASetEvent(p_thread_data->m_reserved_events[1]);	// vector data
		singleLock.Unlock();
	}

	// Keep track of the connect to hosts for when we are checking to see if we can add an ip to the cache
	v_connect_to_ips.clear();
	for(i=0;i<(int)hosts.size();i++)
	{
		v_connect_to_ips.push_back(hosts[i].m_ip);
	}
	
	sort(v_connect_to_ips.begin(),v_connect_to_ips.end());

	// Add these hosts to the connected hosts vector, just so that another mod won't connect to them since i am connecting to them
//	for(i=0;i<hosts.size();i++)
//	{
//		v_connected_host_ips.push_back(hosts[i].IP());
//	}

}
Ejemplo n.º 27
0
int main(int argc, char *argv[])
{
	int retval;
	InitializeCriticalSection(&cs);

	// 윈속 초기화
	WSADATA wsa;
	if(WSAStartup(MAKEWORD(2,2), &wsa) != 0) return 1;

	// socket()
	SOCKET listen_sock = socket(AF_INET, SOCK_STREAM, 0);
	if(listen_sock == INVALID_SOCKET) err_quit("socket()");

	// bind()
	SOCKADDR_IN serveraddr;
	ZeroMemory(&serveraddr, sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
	serveraddr.sin_port = htons(SERVERPORT);
	retval = bind(listen_sock, (SOCKADDR *)&serveraddr, sizeof(serveraddr));
	if(retval == SOCKET_ERROR) err_quit("bind()");

	// listen()
	retval = listen(listen_sock, SOMAXCONN);
	if(retval == SOCKET_ERROR) err_quit("listen()");

	// 더미(dummy) 이벤트 객체 생성
	WSAEVENT hEvent = WSACreateEvent();
	if(hEvent == WSA_INVALID_EVENT)
		err_quit("WSACreateEvent()");
	EventArray[nTotalSockets++] = hEvent;

	// 스레드 생성
	HANDLE hThread = CreateThread(NULL, 0, WorkerThread, NULL, 0, NULL);
	if(hThread == NULL) return 1;
	CloseHandle(hThread);

	// 데이터 통신에 사용할 변수
	SOCKET client_sock;
	SOCKADDR_IN clientaddr;
	int addrlen;
	DWORD recvbytes, flags;

	while(1){
		// accept()
		addrlen = sizeof(clientaddr);
		client_sock = accept(listen_sock, (SOCKADDR *)&clientaddr, &addrlen);
		if(client_sock == INVALID_SOCKET){
			err_display("accept()");
			break;
		}
		printf("\n[TCP 서버] 클라이언트 접속: IP 주소=%s, 포트 번호=%d\n",
			inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));

		// 소켓 정보 추가
		if(AddSocketInfo(client_sock) == FALSE){
			closesocket(client_sock);
			printf("[TCP 서버] 클라이언트 종료: IP 주소=%s, 포트 번호=%d\n",
				inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
			continue;
		}

		// 비동기 입출력 시작
		SOCKETINFO *ptr = SocketInfoArray[nTotalSockets-1];
		flags = 0;
		retval = WSARecv(ptr->sock, &ptr->wsabuf, 1, &recvbytes,
			&flags, &ptr->overlapped, NULL);
		if(retval == SOCKET_ERROR){
			if(WSAGetLastError() != WSA_IO_PENDING){
				err_display("WSARecv()");
				RemoveSocketInfo(nTotalSockets-1);
				continue;
			}
		}

		// 소켓의 개수(nTotalSockets) 변화를 알림
		WSASetEvent(EventArray[0]);
	}

	// 윈속 종료
	WSACleanup();
	DeleteCriticalSection(&cs);
	return 0;
}
Ejemplo n.º 28
0
int
main (
	int		argc,
	char*		argv[]
	)
{
	pgm_error_t* pgm_err = NULL;
#ifdef CONFIG_WITH_HTTP
	gboolean enable_http = FALSE;
#endif
#ifdef CONFIG_WITH_SNMP
	gboolean enable_snmpx = FALSE;
#endif

	setlocale (LC_ALL, "");

/* pre-initialise PGM messages module to add hook for GLib logging */
	pgm_messages_init();
	log_init ();
	g_message ("pgmrecv");

	if (!pgm_init (&pgm_err)) {
		g_error ("Unable to start PGM engine: %s", (pgm_err && pgm_err->message) ? pgm_err->message : "(null)");
		pgm_error_free (pgm_err);
		pgm_messages_shutdown();
		return EXIT_FAILURE;
	}

	g_thread_init (NULL);

/* parse program arguments */
	const char* binary_name = strrchr (argv[0], '/');

	static struct option long_options[] = {
		{ "network",        required_argument, NULL, 'n' },
		{ "service",        required_argument, NULL, 's' },
		{ "port",           required_argument, NULL, 'p' },
		{ "enable-loop",    no_argument,       NULL, 'l' },
#ifdef CONFIG_WITH_HTTP
		{ "enable-http",    no_argument,       NULL, 'H' },
#endif
#ifdef CONFIG_WITH_SNMP
		{ "enable-snmp",    no_argument,       NULL, 'S' },
#endif
		{ "list",           no_argument,       NULL, 'i' },
		{ "help",           no_argument,       NULL, 'h' },
		{ NULL, 0, NULL, 0 }
	};

	int c;
	while ((c = getopt_long (argc, argv, "a:s:n:p:lih"
#ifdef CONFIG_WITH_HTTP
					"H"
#endif
#ifdef CONFIG_WITH_SNMP
					"S"
#endif
					, long_options, NULL)) != -1)
	{
		switch (c) {
		case 'n':	g_network = optarg; break;
		case 'a':	g_source = optarg; break;
		case 's':	g_port = atoi (optarg); break;
		case 'p':	g_udp_encap_port = atoi (optarg); break;

		case 'l':	g_multicast_loop = TRUE; break;
#ifdef CONFIG_WITH_HTTP
		case 'H':	enable_http = TRUE; break;
#endif
#ifdef CONFIG_WITH_SNMP
		case 'S':	enable_snmpx = TRUE; break;
#endif

		case 'i':
			pgm_if_print_all();
			pgm_messages_shutdown();
			return EXIT_SUCCESS;

		case 'h':
		case '?':
			pgm_messages_shutdown();
			usage (binary_name);
		}
	}

#ifdef CONFIG_WITH_HTTP
	if (enable_http) {
		if (!pgm_http_init (PGM_HTTP_DEFAULT_SERVER_PORT, &pgm_err)) {
			g_error ("Unable to start HTTP interface: %s", pgm_err->message);
			pgm_error_free (pgm_err);
			pgm_shutdown();
			pgm_messages_shutdown();
			return EXIT_FAILURE;
		}
	}
#endif
#ifdef CONFIG_WITH_SNMP
	if (enable_snmpx) {
		if (!pgm_snmp_init (&pgm_err)) {
			g_error ("Unable to start SNMP interface: %s", pgm_err->message);
			pgm_error_free (pgm_err);
#ifdef CONFIG_WITH_HTTP
			if (enable_http)
				pgm_http_shutdown ();
#endif
			pgm_shutdown ();
			pgm_messages_shutdown();
	 		return EXIT_FAILURE;
		}
	}
#endif

	g_loop = g_main_loop_new (NULL, FALSE);

	g_quit = FALSE;

/* setup signal handlers */
	signal (SIGSEGV, on_sigsegv);
#ifdef SIGHUP
	signal (SIGHUP,  SIG_IGN);
#endif
#ifdef G_OS_UNIX
	const int e = pipe (g_quit_pipe);
	g_assert (0 == e);
	pgm_signal_install (SIGINT,  on_signal, g_loop);
	pgm_signal_install (SIGTERM, on_signal, g_loop);
#else
	g_quit_event = CreateEvent (NULL, TRUE, FALSE, TEXT("QuitEvent"));
	SetConsoleCtrlHandler ((PHANDLER_ROUTINE)on_console_ctrl, TRUE);
	setvbuf (stdout, (char *) NULL, _IONBF, 0);
#endif

/* delayed startup */
	g_message ("scheduling startup.");
	g_timeout_add (0, (GSourceFunc)on_startup, NULL);

/* dispatch loop */
	g_message ("entering main event loop ... ");
	g_main_loop_run (g_loop);

	g_message ("event loop terminated, cleaning up.");

/* cleanup */
	g_quit = TRUE;
#ifdef G_OS_UNIX
	const char one = '1';
	const size_t writelen = write (g_quit_pipe[1], &one, sizeof(one));
	g_assert (sizeof(one) == writelen);
	g_thread_join (g_thread);
	close (g_quit_pipe[0]);
	close (g_quit_pipe[1]);
#else
	WSASetEvent (g_quit_event);
	g_thread_join (g_thread);
	WSACloseEvent (g_quit_event);
#endif

	g_main_loop_unref (g_loop);
	g_loop = NULL;

	if (g_sock) {
		g_message ("closing PGM socket.");

		pgm_close (g_sock, TRUE);
		g_sock = NULL;
	}

#ifdef CONFIG_WITH_HTTP
	if (enable_http)
		pgm_http_shutdown();
#endif
#ifdef CONFIG_WITH_SNMP
	if (enable_snmpx)
		pgm_snmp_shutdown();
#endif

	g_message ("PGM engine shutdown.");
	pgm_shutdown();
	g_message ("finished.");
	pgm_messages_shutdown();
	return EXIT_SUCCESS;
}
int WinsocketCallbackMain()
{
    WSADATA wsaData;
    SOCKET ListenSocket;
    SOCKADDR_IN InternetAddr;
    INT Ret;
    HANDLE ThreadHandle;
    DWORD ThreadId;
    WSAEVENT AcceptEvent;
 
    if ((Ret = WSAStartup((2,2),&wsaData)) != 0)
    {
        printf("WSAStartup() failed with error %d\n", Ret);
        WSACleanup();
        return 1;
    }
    else
        printf("WSAStartup() is OK!\n");
    
    if ((ListenSocket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
    {
        printf("Failed to get a socket %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("WSASocket() is pretty fine!\n");
 
    InternetAddr.sin_family = AF_INET;
    InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    InternetAddr.sin_port = htons(5150);
 
    if (bind(ListenSocket, (PSOCKADDR) &InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR)
    {
        printf("bind() failed with error %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("bind() is OK!\n");

	if (listen(ListenSocket, 5))
    {
        printf("listen() failed with error %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("listen() is OK!\n");
 
    if ((AcceptEvent = WSACreateEvent()) == WSA_INVALID_EVENT)
    {
        printf("WSACreateEvent() failed with error %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("WSACreateEvent() is OK!\n");

	// Create a worker thread to service completed I/O requests
    if ((ThreadHandle = CreateThread(NULL, 0, WorkerThreadCallback, (LPVOID)AcceptEvent, 0, &ThreadId)) == NULL)
    {
        printf("CreateThread() failed with error %d\n", GetLastError());
        return 1;
    }
    else
        printf("CreateThread() should be fine!\n");

    while(TRUE)
    {
        AcceptSocketCallback = accept(ListenSocket, NULL, NULL);

		/* The WSASetEvent function sets the state 
		 * of the specified event object to signaled. */
        if (WSASetEvent(AcceptEvent) == FALSE)
        {
            printf("WSASetEvent() failed with error %d\n", WSAGetLastError());
            return 1;
        }
        else
            printf("WSASetEvent() should be working!\n");
    }
}
Ejemplo n.º 30
0
LWS_VISIBLE void
lws_cancel_service_pt(struct lws *wsi)
{
	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
	WSASetEvent(pt->events[0]);
}