Esempio n. 1
0
void XSessionWinsock::AcceptThread( void )
{
	SOCKADDR_IN addr; 
	int addrlen; 

	while(1) { 
		addrlen = sizeof(addr); 
		m_Client = accept( m_Socket, (struct sockaddr*)&addr, &addrlen); 

		if( m_Client != INVALID_SOCKET ) 
		{ 
			sprintf_s( m_cIPClient, "%d.%d.%d.%d", 
				addr.sin_addr.S_un.S_un_b.s_b1, addr.sin_addr.S_un.S_un_b.s_b2, 
                addr.sin_addr.S_un.S_un_b.s_b3, addr.sin_addr.S_un.S_un_b.s_b4 );
			//m_PortClient = ntohs(addr.sin_port);
			// call handler
			OnAccept();
			if( m_pDelegate )
				m_pDelegate->DelegateAccept( this );
//			CallEventHandler( xON_ACCEPT );
			// 일단은 클라 하나밖에 못받으니까 걍 리턴
			return;	
		} 
	}
}
Esempio n. 2
0
/**
 * Application must call this if a WM_ is coming from network.
 */
HRESULT ACWinSock::MsgProc(WPARAM wp, LPARAM lp) 
{
	WORD  wEvent, wError;
   
	// get data
	wError = HIWORD(lp);
	wEvent = LOWORD(lp);
   
	// which event
	switch (wEvent) 
	{
		// confirmacao depois de uma conexao bem sucedida
		case FD_CONNECT: break;
         
		// cliente quer aceitacao
		case FD_ACCEPT:  { return OnAccept(); } break;
         
		// recebemos algo
		case FD_READ:    { return OnReceive(wp); } break;
         
		// um cliente ficou offline
		case FD_CLOSE:   { return OnDisconnect(wp); } break;
         
		// nos mandamos algo?
		case FD_WRITE:   break;
	}

	return AC_OK;
};
Esempio n. 3
0
int StartEchoServer(const char* host, const char* port)
{
    SOCKET sockfd, acceptor;
    struct sockaddr_in addr;
    int len = sizeof(addr);

    assert(host && port);
    acceptor = CreateAcceptor(host, port);
    if (acceptor == INVALID_SOCKET)
    {
        return -1;
    }

    for (;;)
    {
        sockfd = accept(acceptor, (struct sockaddr*)&addr, &len);
        if (sockfd == INVALID_SOCKET)
        {
            if (WSAGetLastError() != WSAEWOULDBLOCK)
            {
                fprintf(stderr, "accept() failed, %s.\n", LAST_ERROR_MSG);
                break;
            }
        }
        else
        {
            OnAccept(sockfd);
        }
        Sleep(1);
    }
    return 0;
}
Esempio n. 4
0
bool CPeerBase::Accept(socket_t fd_accept)
{
	struct sockaddr_in peer;

	if ((m_fd = socket_accept(fd_accept, &peer)) == INVALID_SOCKET)
	{
		Destroy();
		return false;
	} 

	//socket_block(m_fd);
	socket_sndbuf(m_fd, 233016);
	socket_rcvbuf(m_fd, 233016);

	strlcpymt(m_host, inet_ntoa(peer.sin_addr), sizeof(m_host));
	m_outBuffer = buffer_new(DEFAULT_PACKET_BUFFER_SIZE);
	m_inBuffer = buffer_new(MAX_INPUT_LEN);

	if (!m_outBuffer || !m_inBuffer)
	{
		Destroy();
		return false;
	}

	fdwatch_add_fd(m_fdWatcher, m_fd, this, FDW_READ, false);

	OnAccept();
	sys_log(0, "ACCEPT FROM %s", inet_ntoa(peer.sin_addr));
	return true;
}
Esempio n. 5
0
int StartEchoServer(const char* host, const char* port)
{
    SOCKET sockfd;
    SOCKET acceptor = CreateAcceptor(host, atoi(port));
    if (acceptor == INVALID_SOCKET)
    {
        return -1;
    }
    for (;;)
    {
        SOCKET sockfd = accept(acceptor, NULL, NULL);
        if (sockfd != SOCKET_ERROR)
        {
            if (OnAccept(sockfd) != 0)
                break;
        }
        else
        {
            if (AsynSelectLoop() != 0)
                break;
        }
    }

    return 0;
}
Esempio n. 6
0
void L2Socket::Acceptor( CChar _ip, CChar _port )
{
    if ( ioService == nullptr ) ioService = new io_service();
    if ( acceptor != nullptr )  delete acceptor;
    
    //LOG( "Acceptor ip: "+_ip+" port: "+_port);
    tcp::resolver _resolver(*ioService);
    // tcp::v4() = 127.0.0.1
    // ip::host_name()
    //address_v4 address = address_v4::from_string(_ip);
    //tcp::endpoint endpoint(address, *_port);
    tcp::resolver::query _query( _ip, _port);
    tcp::endpoint endpoint = *_resolver.resolve(_query);
    //LOG( "Acceptor ip: "+_ip+" port: "+endpoint.port());
    //LOG( "Acceptor ip: "+address.to_string()+" port: "+endpoint.port());
    
    acceptor = new tcp::acceptor(*ioService,endpoint);
    //acceptor = new tcp::acceptor(*ioService);
    //acceptor->open(endpoint.protocol());
    //acceptor->set_option(socket_base::reuse_address(config.reuse_address));
    //acceptor->bind(endpoint);
    //acceptor->listen();

    if(acceptor != nullptr )
        LOG( "Acceptor ip: "+endpoint.address().to_string()+" port: "+endpoint.port());
    else
        LOG( "Acceptor acceptor nullptr!!!" );
    OnAccept();

}
Esempio n. 7
0
// NOTE: Since the old WSAAsync functionality has been exchanged in the favor of WSAEvent, I'm not sure if MsgProc will fire correctly
HRESULT ZFXWS::MsgProc( WPARAM wp, LPARAM lp )
{
   WORD  wEvent, wError;

   wError = HIWORD(lp);
   wEvent = LOWORD(lp);

   //evaluate what event occurred
   switch ( wEvent )
   {
      //new client accepted
      case FD_CONNECT:
         break;
      
      //new client is knocking
      case FD_ACCEPT:
         return OnAccept();
         break;

      //there is data to be received
      case FD_READ:
         return OnReceive(wp);
         break;

      //a socket is closing
      case FD_CLOSE:
         return OnDisconnect(wp);
         break;

      //after sending data
      case FD_WRITE:
         break;
   }
   return ZFX_OK;
}
Esempio n. 8
0
void L2Socket::HandleAccept( tcp::socket& _socket, boost::system::error_code _ec )
{
    if (!acceptor->is_open() )
    {
        LOG( "HandleAccept acceptor !is_open()!!!" );
        return ;
    }
    if( _ec )
    {
        LOG( "HandleAccept error: "+ _ec.message() );
        Disconnect(_socket);
        return;
    }
    LOG( "HandleAccept New Connect ip: "+_socket.remote_endpoint().address().to_string() + " port: " + _socket.remote_endpoint().port());
    
    //tcp::no_delay option(true);
    //_socket.set_option(option);

    shared_ptr<L2Actor> _act = L2_GET_UNUSED_OBJ(L2Actor);
    
    SERVER->PushActor( _act->OID );
    
    _act->GetAgent()->SetConnect(true);
    sockAry.push_back(&_socket);
    agentOIDAry.push_back( _act->GetAgent()->OID );
    
    if( bWebSocket )
        OnHandshake(_socket,_act->GetAgent()->OID);
    else
        OnReceive( _socket,_act->GetAgent()->OID );
    
    //THREAD->ThreadSleepFPS();
    OnAccept();
}
BOOL CXTPPropertyGridInplaceMonthCal::OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
	if (message == WM_KILLFOCUS)
	{
		CWnd* pWnd = CWnd::FromHandle((HWND)wParam);
		if (pWnd && IsChild(pWnd))
		{
			return CWnd::OnWndMsg(message, wParam, lParam, pResult);
		}

		OnCancel();
		return TRUE;
	}
	if (message == WM_KEYDOWN && wParam == VK_ESCAPE)
	{
		OnCancel();
		return TRUE;
	}
	if (message == WM_KEYDOWN && wParam == VK_RETURN)
	{
		OnAccept();
		return TRUE;
	}

	return CWnd::OnWndMsg(message, wParam, lParam, pResult);
}
void
ModInfoDlg::ExecFrame()
{
	if (Keyboard::KeyDown(VK_RETURN)) {
		if (btn_accept && btn_accept->IsEnabled())
		OnAccept(0);
	}
}
Esempio n. 11
0
	void Acceptor::Start()
	{
		//начинаем слушать сокет
		asioAcceptor.async_accept(socket,
			[this](const system::error_code &_errorCode)
		{
			OnAccept(_errorCode);
		});
	}
Esempio n. 12
0
void CListenSocket::ReStartListening()
{
	// 0.42e
	bListening = true;
	if (m_nPendingConnections) {
		m_nPendingConnections--;
		OnAccept(0);
	}
}
Esempio n. 13
0
void CAsyncSocketExLayer::CallEvent(int nEvent, int nErrorCode)
{
	if (m_nCriticalError)
		return;
	m_nCriticalError=nErrorCode;
	switch (nEvent)
	{
	case FD_READ:
	case FD_FORCEREAD:
		if (GetLayerState()==connected)
		{
			if (nErrorCode)
				SetLayerState(aborted);
			OnReceive(nErrorCode);
		}
		break;
	case FD_WRITE:
		if (GetLayerState()==connected)
		{
			if (nErrorCode)
				SetLayerState(aborted);
			OnSend(nErrorCode);
		}
		break;
	case FD_CONNECT:
		if (GetLayerState()==connecting)
		{
			if (!nErrorCode)
				SetLayerState(connected);
			else
				SetLayerState(aborted);
			OnConnect(nErrorCode);
		}
		break;
	case FD_ACCEPT:
		if (GetLayerState()==listening)
		{
			if (!nErrorCode)
				SetLayerState(connected);
			else
				SetLayerState(aborted);
			OnAccept(nErrorCode);
		}
		break;
	case FD_CLOSE:
		if (GetLayerState()==connected)
		{
			if (nErrorCode)
				SetLayerState(aborted);
			else
				SetLayerState(closed);
			OnClose(nErrorCode);
		}
		break;
	}
}
TargetWindowDlg::TargetWindowDlg(QWidget* parent) : QDialog(parent){
	setupUi(this);
	QStringList windowTitles = autoType->getAllWindowTitles();
	windowTitles.sort();
	for (QStringList::const_iterator i = windowTitles.constBegin(); i != windowTitles.constEnd(); ++i)
		comboWindow->addItem(*i);
	
	connect(buttonBox, SIGNAL(accepted()), SLOT(OnAccept()));
	connect(buttonBox, SIGNAL(rejected()), SLOT(reject()));
}
Esempio n. 15
0
void CListenSocket::ReStartListening()
{
	bListening = true;

	ASSERT( m_nPendingConnections >= 0 );
	if (m_nPendingConnections > 0)
	{
		m_nPendingConnections--;
		OnAccept(0);
	}
}
TargetWindowDlg::TargetWindowDlg(QWidget* parent) : QDialog(parent){
	setupUi(this);
	QStringList windowTitles = autoType->getAllWindowTitles();
#ifndef Q_WS_MAC
	// on MacX, titles are in top to bottom order which is better than alpha order so no sort
	windowTitles.sort();
#endif
	for (QStringList::const_iterator i = windowTitles.constBegin(); i != windowTitles.constEnd(); ++i)
		comboWindow->addItem(*i);
	
	connect(buttonBox, SIGNAL(accepted()), SLOT(OnAccept()));
	connect(buttonBox, SIGNAL(rejected()), SLOT(reject()));
}
Esempio n. 17
0
void Server::HandleAccept(const boost::system::error_code& errCode)
{
	OnAccept();
	static int iCount = 0;
	if (!errCode)
	{
		std::string timeStr;
		GetCurrentStringTime(timeStr);
		std::cout<<timeStr<<"::Server::HandleAccept::New Connection Coming--->iCount="<<iCount++<<std::endl;
		m_connectionPtr->OnStart();
	}
	
}
Esempio n. 18
0
/*
 * 处理Accept
 */
int TCPServer_Accept(TCPServer* pServer)
{
	if(pServer == NULL)
	{
		return -1;
	}

	// step 1: accept接收新连接
	sockaddr_in stAddr;
	memset(&stAddr, 0, sizeof(stAddr));
	int iLen = sizeof(stAddr);
	int iSock = socketapi_accept(pServer->iServSocket, (struct sockaddr*)&stAddr, (socklen_t*)&iLen);
	if(iSock == -1)
	{
		if(errno == EAGAIN || errno == EINTR)
		{
			return 0;
		}

		XLOG_ERROR(pServer->pLogger, "[error] accept error: (%s).", strerror(errno));
		return -2;
	}

	// step 2: 置为非阻塞
	int iRet = socketapi_setnonblocking(iSock, 1);
	if(iRet < 0)
	{
		XLOG_ERROR(pServer->pLogger, "SetNonBlocking() fail: %d", iRet);
		return -3;
	}

	// step 3: 添加事件
	iRet = Epoller_EventAdd(pServer->pEpoller, iSock, EVENT_READ | EVENT_ERROR);
	if(iRet < 0)
	{
		XLOG_ERROR(pServer->pLogger, "EventAdd() fail: %d", iRet);
		socketapi_close(iSock);
		return -4;
	}

	// 额外工作,留出API (不退出程序)
#if 0
	iRet = OnAccept(iSock);
	if(iRet < 0)
	{
		XLOG_ERROR(m_pLogger, "OnAccept() fail: %d", iRet);
	}
#endif

	return 0;
}
 void TcpServer::AcceptHandler(std::shared_ptr<TcpPeerConnection> acceptedConn, const boost::system::error_code& ec)
 {
     if (ec != 0)
     {
         LOG() << "Accept error: " << ec << std::endl;
         // Review: call an error callback.
     }
     else {
         OnAccept(acceptedConn);
     }
     
     // Kick off another async accept to handle another connection.
     AsyncAccept();
 }
Esempio n. 20
0
void ServerSocket::Accept(void) {
	int sd;
	
	sd = accept(_sd, NULL, NULL);
	if(sd < 0) 
		printf("error\n");
	if(!fork()){
		IOSocket *pSocket = new IOSocket(sd);
		OnAccept(pSocket);
	}
	else{
		close(sd);
 	}
}
Esempio n. 21
0
void EgSock::_OnRead() 
{
	if (_state == EG_SOCK_STATE_LISTENING) {
		OnAccept();
	} else {
		uint64_t avail;
		if ((ioctl(fd, FIONREAD, &avail) == SOCKET_ERROR) || (avail == 0)) {
		    _event = EG_SOCK_EVENT_CLOSE;
			OnClose(fd);
		} else {
			_event = EG_SOCK_EVENT_READ;
			_callback(shared_from_this());
		}
	}
}
    void TcpServer::HandleSslHandshake(std::shared_ptr<TcpSslConnection>acceptedConn, const boost::system::error_code& error) {
        if (!error)
        {
            LOG() << "handle handshake" << std::endl;
            OnAccept(acceptedConn);
        }
        else
        {
            SSL_load_error_strings();
            unsigned long n = ERR_get_error();
            char buf[1024];
			auto err = ERR_error_string(n, buf);
			LOG() << "Handle SSL handshake error: " << err << std::endl;
        }
        
    }
Esempio n. 23
0
INT_PTR KBIntDialog::OnCommand(int ctrlId, int notifCode, HWND idHwnd) {
	if (ctrlId == IDOK) {
		int ret = OnAccept();
		if (ret == 0)
			EndDialog(m_hwnd, 1);
		else
			EndDialog(m_hwnd, 2);
		return TRUE;
	} else if (ctrlId == IDCANCEL) {
		OnCancel();
		EndDialog(m_hwnd, 2);
		return TRUE;
	}

	return Dialog::OnCommand(ctrlId, notifCode, idHwnd);
}
Esempio n. 24
0
void Server::PostAccept()
{
    // If the number of clients is too big, we can just stop posting accept.
    // That's one of the benefits from AcceptEx.
    int count = m_MaxPostAccept - m_NumPostAccept;
    if (count > 0)
    {
        int i = 0;
        for (; i < count; ++i)
        {
            Client* client = new Client();
            if (!client->Create())
            {
                delete client;
                break;
            }

            IOEvent* event = IOEvent::Create(IOEvent::ACCEPT, client);
            assert(event);

            StartThreadpoolIo(m_pTPIO);
            if (!Network::AcceptEx(m_listenSocket, client->GetSocket(), &event->GetOverlapped()))
            {
                int error = WSAGetLastError();

                if (error != ERROR_IO_PENDING)
                {
                    CancelThreadpoolIo(m_pTPIO);

                    ERROR_CODE(error, "AcceptEx() failed.");
                    delete client;
                    IOEvent::Destroy(event);
                    break;
                }
            }
            else
            {
                OnAccept(event);
                IOEvent::Destroy(event);
            }
        }

        InterlockedExchangeAdd(&m_NumPostAccept, i);

        TRACE("[%d] Post AcceptEx : %d", GetCurrentThreadId(), m_NumPostAccept);
    }
}
void
MsnElemDlg::ExecFrame()
{
	if (Keyboard::KeyDown(VK_RETURN)) {
		if (!exit_latch && btn_accept && btn_accept->IsEnabled())
		OnAccept(0);
	}

	else if (Keyboard::KeyDown(VK_ESCAPE)) {
		if (!exit_latch)
		OnCancel(0);
	}

	else {
		exit_latch = false;
	}
}
Esempio n. 26
0
bool AFMServer::AcceptConnection()
{
    int rc = 0;
    fd_set readset;

    FD_ZERO(&readset);
    FD_SET(m_hSocket, &readset);

    rc = select(m_hSocket+1, &readset, NULL, NULL, NULL);

    if (rc > 0) {
        OnAccept(errno);
    } else {
        EMSVRLOG("Select return abnormal rc:%d, errno:%d, err_msg:%s", rc, errno, strerror(errno));
    }
    return rc > 0 ? true : false;

}
Esempio n. 27
0
void WndProc(int message)
{ 
	switch (message) {
	case 0:
		// Nothing to do...
		break;
#if 0
	case WM_USER_TIMERSIGNAL:
		if (wParam == G_mmTimer0) G_pGateCore->OnTimer(0);
		break;
#endif
	case WM_USER_ACCEPT:
		OnAccept();
		break;
#if 0
	case WM_KEYDOWN:
		G_pGateCore->OnKeyDown(wParam, lParam);
		break;

	case WM_KEYUP:
		G_pGateCore->OnKeyUp(wParam, lParam);
		break;

	case WM_PAINT:
		OnPaint();
		break;

	case WM_DESTROY:
		OnDestroy();
		break;

	case WM_CLOSE:
		if (MessageBox(NULL, "Quit gate server?", "GATE-SERVER", MB_ICONEXCLAMATION | MB_YESNO) == IDYES) {
			return (DefWindowProc(hWnd, message, wParam, lParam));
		}
		break;
#endif
	default: 
		if ((message >= WM_ONCLIENTSOCKETEVENT) && (message < WM_ONCLIENTSOCKETEVENT + DEF_MAXCLIENTS)) 
			G_pGateCore->OnClientSocketEvent(message, 0, 0); // , wParam, lParam);

		break;
	}
}
Esempio n. 28
0
/*========================================================================================
	FUNCTION: LBaseSock::WindowProc()
	DESCRIPT: Event handler window procedure.
	RETURN	:
	ARGUMENT:
		uMsg  : (i)Message ID
		wParam: (i)Message parameter 1
		lParam: (i)Message parameter 2
	UPDATE	: 2004/07/01, In-hyeok Paek; First work!
========================================================================================*/
LRESULT LBaseSock::WindowProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) 
{
	int		nErr;	//	Socket error code
	
	if( uMsg == WM_SOCK_SOCKET ) {
		nErr =  WSAGETASYNCERROR( lParam );
		switch( WSAGETSELECTEVENT( lParam ) ) {
			case FD_ACCEPT:
				OnAccept( nErr );
				break;
			case FD_CONNECT: 
				::KillTimer( m_hWnd, IDT_SOCK_CONNECT );
				OnConnect( nErr ); 
				break;
			case FD_CLOSE:
				OnClose( nErr );
				break;
			case FD_READ:
				OnReceive( nErr );
				break;
			case FD_WRITE:
				OnSend( nErr );
				break;
		}
		return 0L;
	}
	else if( uMsg == WM_TIMER ) {
		if( wParam == IDT_SOCK_CONNECT ) {
			if( m_Sock != INVALID_SOCKET ) {
				closesocket( m_Sock );
				m_Sock = INVALID_SOCKET;
			}
			m_nLastErr = WSAETIMEDOUT;
			OnConnect( WSAETIMEDOUT );
			return 0L;
		}
		
	}

	return ::DefWindowProc( m_hWnd, uMsg, wParam, lParam );
}
Esempio n. 29
0
Server::Server(const std::string& address, const std::string& port, const int iPoolSize)
	:m_io_AsioPool(iPoolSize)
	, m_work_AsioPool(1)
	,m_acceptor(m_io_AsioPool.GetIoService())
	,m_signalSet(m_work_AsioPool.GetIoService() )
{
	m_signalSet.add(SIGINT);
	m_signalSet.add(SIGTERM);
	m_signalSet.async_wait(boost::bind(&Server::HandleStop, this));

	boost::asio::ip::tcp::resolver resolver(m_acceptor.get_io_service());
	boost::asio::ip::tcp::resolver::query query(address, port);
	boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
	m_acceptor.open(endpoint.protocol());
	m_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
	m_acceptor.bind(endpoint);
	m_acceptor.listen(99999);

	OnAccept();

}
Esempio n. 30
0
void WAsyncSocket::SocketMessage(WPARAM wparam,LPARAM lparam)
{
	// wparam is the socket number, lparam is the event code (lower word) and error code (upper word)
	int event_code=WSAGETSELECTEVENT(lparam);	// lower word of lparam
	int error_code=WSAGETSELECTERROR(lparam);	// upper word of lparam

	switch(event_code)
	{
		case FD_CONNECT:
		{
			OnConnect(error_code);
			break;
		}
		case FD_ACCEPT:
		{
			OnAccept(error_code);
			break;
		}
		case FD_READ:
		{
			OnReceive(error_code);
			break;
		}
		case FD_WRITE:
		{
			OnSend(error_code);
			break;
		}
		case FD_CLOSE:
		{
			OnClose(error_code);
			break;
		}
		default:
		{
			// Unknown Socket Message
			break;
		}
	}
}