Esempio n. 1
0
bool IocpTransmitStrategy::HandleRecvSuccess(const IocpOperation* iocpOperation
    , DWORD byteNumber) {
    MZ_ASSERT_TRUE(&m_recvOperation == iocpOperation);

    auto& socketBuffer = m_transmitSocket.TheSocketBuffer();

    const auto planLength = socketBuffer.m_recvPlan.GetCurLength();
    const auto cacheLength = socketBuffer.m_recvCache.GetCurLength();
    //NS_SHARE::Log(MZ_LOG_DEBUG, "Socket Recv: plan[%d] cache[%d]. [%s:%d]\n", planLength, cacheLength, __FILE__, __LINE__);

    if (byteNumber == 0) {
        NS_SHARE::Log(MZ_LOG_DEBUG, "Socket Info: socket close. [%s:%d]\n", __FILE__, __LINE__);
        m_transmitSocket.Close();
        return true;
    }

    const auto recvData = nullptr;
    const auto recvLength = byteNumber;

    m_transmitSocket.OnRecved(recvData, recvLength);

    const auto restLength = socketBuffer.PreserveRecvPlan(byteNumber);
    if (restLength > 0) {
        NS_SHARE::Log(MZ_LOG_DEBUG, "Socket Trace: socket close. [%s:%d]\n", __FILE__, __LINE__);
        m_transmitSocket.Disconnect();
        return false;
    }

    return PostRecv();
}
Esempio n. 2
0
bool ClientSession::OnConnect(SOCKET socket, SOCKADDR_IN* addr)
{
	FastSpinlockGuard criticalSection(mSessionLock);

	CRASH_ASSERT(LIoThreadId == MAIN_THREAD_ID);

	mSocket = socket;

	/// make socket non-blocking
	u_long arg = 1 ;
	ioctlsocket(mSocket, FIONBIO, &arg) ;

	/// turn off nagle
	int opt = 1 ;
	setsockopt(mSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof(int)) ;

	/// create socket RQ
	/// SEND and RECV within one CQ (you can do with two CQs, seperately)
	mRequestQueue = RIO.RIOCreateRequestQueue(mSocket, MAX_RECV_RQ_SIZE_PER_SOCKET, 1, MAX_SEND_RQ_SIZE_PER_SOCKET, 1,
		GRioManager->GetCompletionQueue(mRioThreadId), GRioManager->GetCompletionQueue(mRioThreadId), NULL);
	if (mRequestQueue == RIO_INVALID_RQ)
	{
		printf_s("[DEBUG] RIOCreateRequestQueue Error: %d\n", GetLastError());
		return false ;
	}

	memcpy(&mClientAddr, addr, sizeof(SOCKADDR_IN));
	mConnected = true ;

	printf_s("[DEBUG] Client Connected: IP=%s, PORT=%d\n", inet_ntoa(mClientAddr.sin_addr), ntohs(mClientAddr.sin_port));

	return PostRecv() ;
}
Esempio n. 3
0
bool CIOCP::_DoWrite(PER_SOCKET_CONTEXT* pSocketContext, PER_IO_CONTEXT* pIoContext)
{
	if (pIoContext->m_nSendBytes < pIoContext->m_nTotalBytes)
	{
		//数据未能发送完,继续发送数据
		WSABUF* p_wbuf = &pIoContext->m_wsaBuf;
		p_wbuf->buf += pIoContext->m_nSendBytes;
		p_wbuf->len -= pIoContext->m_nSendBytes;
		PostWrite(pSocketContext,pIoContext);
	}
	else
	{
		NODEBUF* pNode = pIoContext->m_listBuf.pNode;
		pNode = pNode->pNext;
		if(pNode&&pNode->len>0)
		{
			WSABUF* p_wbuf = &pIoContext->m_wsaBuf;
			p_wbuf->buf = pNode->buf;
			p_wbuf->len = pNode->len;
			PostWrite(pSocketContext,pIoContext);
		}
		else
		{
			pIoContext->ResetBuffer();
			PostRecv(pSocketContext,pIoContext);
		}
	}
	return TRUE;
}
Esempio n. 4
0
void ProactorService::open( ACE_HANDLE h, ACE_Message_Block& MessageBlock )
{
	this->handle(h);	

	if (this->m_AsyncReader.open(*this) != 0 || this->m_AsyncWriter.open(*this) != 0)
	{
		delete this;
		return;
	}
	
	m_pTimerLock = new InterlockedValue();
	m_pTimerLock->Release();

	m_bServiceCloseFlag = false;

	m_Serial = ProactorServiceMapSingleton::instance()->Register(this);

	assert(m_Serial != INVALID_ID);

	RegisterTimer();

	ISession::OnConnect(this->m_Serial);

	PostRecv();
}
Esempio n. 5
0
void EasyIocp::PushToDebug(CompTransmitKey *transKey)
{
	sockaddr_in serverAddr, clientAddr;
	char data[EASYIOCP_MAX_BUFF];
	const char *operType;
	DWORD len;

	transKey->GetBothAddr(&serverAddr, &clientAddr);

	EasyIocpBuffer *iocpBuffer = transKey->GetBuffer();
	len = iocpBuffer->GetBody(data, EASYIOCP_MAX_BUFF);
	data[len] = 0;

	if(transKey->GetOperType() == operRecv) {
		operType = "recv";

		print("%s:%d %s from %s:%d, data: %s", 
			inet_ntoa(serverAddr.sin_addr), ntohs(serverAddr.sin_port), operType,
			inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), data);

		PostSend(transKey->GetSocket(), data, len);
	}
	else if(transKey->GetOperType() == operSend) {
		/*operType = "send";
		print("%s:%d %s to %s:%d, data:%s", 
			inet_ntoa(serverAddr.sin_addr), ntohs(serverAddr.sin_port), operType,
			inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), data);*/

		PostRecv(transKey);
	}
	else {
		print("EasyIocp::PushToDebug: invalid oper.");
	}
}
Esempio n. 6
0
int CNTReader::SendCommand(const byte *sbuff,short slen,unsigned char * rbuff,short *rlen,int timeout)
{
    unsigned char sCmd[512]= {0},sResp[512]= {0};
    int  nCmdLen=0;
    if(!IsOpen())
        return PORT_NOTOPEN_ERROR;
    sCmd[0]=0x02;
    sCmd[1]=slen/256;
    sCmd[2]=slen%256;
    memcpy(sCmd+3,sbuff,slen);
    nCmdLen=3+slen;
    sCmd[nCmdLen]=XOR(sbuff,slen);
    nCmdLen++;
    sCmd[nCmdLen]=0x03;
    nCmdLen++;
    if( !PostSend(sCmd,nCmdLen,timeout))
    {
        return SEND_DATA_ERROR;
    }
    //Sleep(80);
    if( !PostRecv(sResp,sizeof(sResp),timeout))
    {
        return RECV_DATA_ERROR;
    }
//Resp:数据长度(2字节)+状态码(2字节)+数据
    *rlen=sResp[0]*256+sResp[1]-2;	//去掉2字节状态码
    if(*rlen>256)
        *rlen=256;
    if(*rlen>0) memcpy(rbuff,sResp+4,*rlen);
    return sResp[2]*256+sResp[3];
}
Esempio n. 7
0
void Server::OnRecv(IOEvent* event, DWORD dwNumberOfBytesTransfered)
{
    assert(event);

    TRACE("[%d] Enter OnRecv()", GetCurrentThreadId());

    BYTE* buff = event->GetClient()->GetRecvBuff();
    buff[dwNumberOfBytesTransfered] = '\0';
    TRACE("[%d] OnRecv : %s", GetCurrentThreadId(), buff);

    // Create packet by copying recv buff.
    Packet* packet = Packet::Create(event->GetClient(), event->GetClient()->GetRecvBuff(),
                                    dwNumberOfBytesTransfered);

    // If whatever logics relying on the packet are fast enough, we can manage them here but
    // assume they are slow.
    // it's better to request receiving ASAP and handle packets received in another thread.
    if (!TrySubmitThreadpoolCallback(Server::WorkerProcessRecvPacket, packet, NULL))
    {
        ERROR_CODE(GetLastError(), "Could not start WorkerProcessRecvPacket. call it directly.");

        Echo(packet);
    }

    PostRecv(event->GetClient());

    TRACE("[%d] Leave OnRecv()", GetCurrentThreadId());
}
Esempio n. 8
0
int Connections::CompleteConnect(DWORD TransferedBytes)
{
    FUNCTION_BEGIN();

    UNREFERENCED_PARAMETER(TransferedBytes);

    _socket.GetPeerAddr(_remoteAddr);
    _socket.GetLocalAddr(_localAddr);
    _IsConnected = true;

    int rc = _NetworkRef->Associate(this, true);
    if (0 != rc)
    {
        Logger::Log("Session[%X] CompleteConnect Error[%d]\n", this, rc);
        return rc;
    }

    SetStatus(CONNSTATUS_ACTIVE);
    _ConnectTime = GetTickCount();
    _ConnectorRef->OnConnected();
    _NetworkRef->PostNetEventMessage((WPARAM)NETEVENT_CONNECT, (LPARAM)this);


    rc = PostRecv();
    if (0 != rc)
    {
        return rc;
    }

    return 0;
}
Esempio n. 9
0
void 
EasyIocp::DoAcceptWithoutData(CompListenKey *listenKey, int index, sockaddr_in *serverAddr, sockaddr_in *clientAddr)
{
	//acceptSock是用来和客户端进行收发数据的socket
	SOCKET acceptSock = listenKey->GetOneAcceptSock(index);
	if(acceptSock == INVALID_SOCKET) {
		print("EasyIocp::DoAcceptWithData: acceptSock is INVALID_SOCKET.");
		return;
	}

	CompTransmitKey *transKey = easyClients_.NewClient(acceptSock, serverAddr, clientAddr);
	if(!transKey) {
		print("EasyIocp::DoAcceptWithData: invalid transKey.");
		return;
	}

	//关联套接字与完成端口
	if(!CreateIoCompletionPort((HANDLE)acceptSock, hCompPort_, (ULONG_PTR)transKey, 0)) {
		ErrorSysMessage("EasyIocp::DoAcceptWithData: associate socket failed.");
		easyClients_.RemoveClient(acceptSock);
		return;
	}

	PostRecv(transKey);
}
Esempio n. 10
0
///函数:投递一个recv请求。
bool 
EasyIocp::PostRecv(SOCKET transSock)
{
	CompTransmitKey *transKey = easyClients_.FindClient(transSock);
	if(!transKey)
		return false;

	return PostRecv(transKey);
}
Esempio n. 11
0
bool CIOCP::_DoRecv( PER_SOCKET_CONTEXT* pSocketContext, PER_IO_CONTEXT* pIoContext )
{
	OnReadCompleted(pSocketContext, pIoContext);
	NODEBUF* pNode = pIoContext->m_listBuf.pNode;
	pNode->len += pIoContext->m_nTotalBytes;
	PostRecv(pSocketContext, pIoContext);
	//iocp性能太高了,要一
	return true;
}
Esempio n. 12
0
void ProactorService::open( ACE_HANDLE h, ACE_Message_Block& MessageBlock )
{
	this->handle(h);	

	if (this->m_AsyncReader.open(*this) != 0 || this->m_AsyncWriter.open(*this) != 0)
	{
		delete this;
		return;
	}
	
	m_pTimerLock = new InterlockedValue();
	m_pTimerLock->Release();

	m_bServiceCloseFlag = false;

	if (g_currentSessionCnt > GetEngine()->GetMaxUserAccept())
	{
		if (this->handle() != ACE_INVALID_HANDLE)
			ACE_OS::closesocket(this->handle());

		this->handle(ACE_INVALID_HANDLE);

		delete this;
		return;
	}

	m_serial = ProactorServiceManagerSinglton::instance()->Register(this);	

	if (m_serial == INVALID_ID)
	{
		if (this->handle() != ACE_INVALID_HANDLE)
			ACE_OS::closesocket(this->handle());

		this->handle(ACE_INVALID_HANDLE);
		
		delete this;
		return;
	}

	RegisterTimer();

	sockaddr_in addr;
	int addrLen = sizeof(addr);

	ACE_OS::getpeername(this->handle(), (sockaddr *)&addr, &addrLen);	

	m_sessionDesc.port = ntohs(addr.sin_port);
	char* szIP = inet_ntoa(addr.sin_addr);

	if(szIP != NULL)
		m_sessionDesc.szIP = inet_ntoa(addr.sin_addr);


	ISession::OnConnect(this->m_serial, m_sessionDesc);

	PostRecv();
}
Esempio n. 13
0
//-----------------------------------------------------------------------------------
//		Purpose	:
//		Return	:
//-----------------------------------------------------------------------------------
// Called by Worker TH ( IOCP )
//-----------------------------------------------------------------------------------
int CNtlConnection::CompleteAccept(DWORD dwTransferedBytes)
{
	FUNCTION_BEGIN();

	UNREFERENCED_PARAMETER( dwTransferedBytes );

	SOCKADDR_IN * pLocalAddr = NULL;
	SOCKADDR_IN * pRemoteAddr = NULL;
	int nLocalAddrLen = 0;
	int nRemoteAddrLen = 0;

	m_socket.GetAcceptExSockaddrs(	m_recvContext.wsabuf.buf,
									0,
									sizeof(SOCKADDR_IN) + 16,
									sizeof(SOCKADDR_IN) + 16,
									(SOCKADDR**) &pLocalAddr,
									&nLocalAddrLen,
									(SOCKADDR**) &pRemoteAddr,
									&nRemoteAddrLen);

	SetAddress( pLocalAddr, pRemoteAddr );
	ZeroMemory( m_recvContext.wsabuf.buf, sizeof(SOCKADDR_IN) + 16 + sizeof(SOCKADDR_IN) + 16 );
	m_bConnected = true;

	int rc = m_pNetworkRef->Associate( this, true );
	if( NTL_SUCCESS != rc )
	{
		NTL_LOGDL( LOG_NETWORK, "Session[%X] Associate Error[%d:%s]", this, rc, NtlGetErrorMessage(rc) );
		return rc;
	}


	SetStatus( STATUS_ACTIVE );
	m_dwConnectTime = GetTickCount();


	m_pAcceptorRef->OnAccepted();


	m_pNetworkRef->PostNetEventMessage( (WPARAM)NETEVENT_ACCEPT, (LPARAM)this );


	rc = PostRecv();
	if( NTL_SUCCESS != rc )
	{
		return rc;
	}


	//NTL_PRINT(PRINT_SYSTEM, "Session[%X]\tCompleteAccept Called Local[%s:%u] Remote[%s:%u]", pSession, GetLocalIP(), GetLocalPort(), GetRemoteIP(), GetRemotePort());


	return NTL_SUCCESS;
}
Esempio n. 14
0
bool IocpTransmitStrategy::PostInput() {
    if (!m_transmitSocket.IsWorking()) {
        return false;
    }

    if (m_recvOperation.IsBusy()) {
        return true;
    }

    m_recvOperation.SetBusy(true);

   return PostRecv();
}
Esempio n. 15
0
void 
EasyIocp::DoRecv(CompTransmitKey *transKey, DWORD transBytes)
{
	EasyIocpBuffer *iocpBuffer = transKey->GetBuffer();
	
	iocpBuffer->AddTransBytes(transBytes);
	if(iocpBuffer->IsTransComplete()) {
		//数据接收完毕
		//PushToBusiness(transKey);
		PushToDebug(transKey);
	}else {
		PostRecv(transKey, false);	//数据未接收完毕,则继续接收
	}
}
	void Sock5Relay::OnConnect(INT iErrorCode)
	{
		//连接失败
		if (0 != iErrorCode)
		{
			//连接代理服务器失败
			if (STATE_CONNECT_SER == m_nState)
			{
				InterlockedExchange(&m_nState, STATE_RELAY_FAILE);
			}
		}
		//连接成功
		else if (STATE_CONNECT_SER == m_nState)
		{		
			//成功连接到代理服务器, 向服务器发送认证信息
			//版本号(1字节) | 可供选择的认证方法(1字节) | 方法序列(1-255个字节长度)

			//投递读操作
			if (FALSE == PostRecv(m_pRcvContext, m_hSock))
			{
				InterlockedExchange(&m_nState, STATE_RELAY_FAILE);
				return;
			}

			CHAR szBuf[512];
			SOCK5REQ1* pReq1 = (SOCK5REQ1*)szBuf;
			INT nLen = 0;
			if (FALSE == m_bAuth)
			{
				pReq1->Ver = 0x05;
				pReq1->nMethods = 0x01;
				pReq1->Methods[0] = 0x00;
				nLen = 3;				
			}
			else
			{
				pReq1->Ver = 0x05;
				pReq1->nMethods = 0x01;
				pReq1->Methods[0] = 0x02;
				nLen = 3;
			}			

			InterlockedExchange(&m_nState, STATE_RELAY_STEP_1);

			if (FALSE == CRelay::Send(szBuf, nLen))
			{
				InterlockedExchange(&m_nState, STATE_RELAY_FAILE);
			}		
		}
	}
Esempio n. 17
0
static int32_t imp_engine_add(engine *e,handle *h,generic_callback callback)
{
	int32_t ret;
	assert(e && h && callback);
	if(h->e) return -EASSENG;
	//call the base_engine_add first
	ret = base_engine_add(e,h,(generic_callback)IoFinish);
	if(ret == 0){
		((datagram*)h)->on_packet = (void(*)(datagram*,packet*,sockaddr_*))callback;
		//post the first recv request
		if(!(((socket_*)h)->status & RECVING))
			PostRecv((datagram*)h);
	}
	return ret;
}
int MightyTCPCompletionPortServer::InsertSocketObj(PCompletionPortIOObject pSocket)
{

		//GUID guid_val;
		string guid_strkey=P2PUtilTools::GetStringUuid();
		pSocket->identityIDKey=guid_strkey;
		m_ActiveSocketMap.insert(map<string,PCompletionPortIOObject>::value_type(guid_strkey,pSocket));
		//nSocketCount++;
		PCompletionPort_BufObj pIOBuf=AllocateBuffer(pSocket,4096);
		PostRecv(pIOBuf);
		m_pNotifyCallBack->OnAccept(guid_strkey);
		return 0;

	
}
Esempio n. 19
0
int Connections::CompleteAccept(DWORD TransferedBytes)
{
    FUNCTION_BEGIN();

    UNREFERENCED_PARAMETER(TransferedBytes);

    SOCKADDR_IN* LocalAddr = NULL;
    SOCKADDR_IN* RemoteAddr = NULL;
    int LocalAddrLen = 0;
    int RemoteAddrLen = 0;

    _socket.GetAcceptExSockaddrs(_recvContext.wsabuf.buf,
                                 0,
                                 sizeof(SOCKADDR_IN) + 16,
                                 sizeof(SOCKADDR_IN) + 16,
                                 (SOCKADDR**)&LocalAddr,
                                 &LocalAddrLen,
                                 (SOCKADDR**)&RemoteAddr,
                                 &RemoteAddrLen);

    SetAddress(LocalAddr, RemoteAddr);
    ZeroMemory(_recvContext.wsabuf.buf, sizeof(SOCKADDR_IN) + 16 + sizeof(SOCKADDR_IN) + 16);
    _IsConnected = true;

    int rc = _NetworkRef->Associate(this, true);
    if (0 != rc)
    {
        Logger::Log("Session[%X] Associate Error[%d]\n", this, rc);
        return rc;
    }

    SetStatus(CONNSTATUS_ACTIVE);
    _ConnectTime = GetTickCount();

    Logger::Log("Client connected %s:%d [%d]\n", GetRemoteIP(), GetRemotePort(), this);

    _AcceptorRef->OnAccepted();

    _NetworkRef->PostNetEventMessage((WPARAM)NETEVENT_ACCEPT, (LPARAM)this);

    rc = PostRecv();
    if (0 != rc)
    {
        return rc;
    }

    return 0;
}
Esempio n. 20
0
static void IoFinish(handle *sock,void *_,int32_t bytes,int32_t err_code,int32_t recvflags)
{
	int32_t unpack_err;
	datagram *d = (datagram*)sock;	
	if(bytes > 0 && recvflags != MSG_TRUNC){
		update_next_recv_pos(d,bytes);
		packet *pk = d->decoder_->unpack(d->decoder_,&unpack_err);
		if(pk){
			d->on_packet(d,pk,&d->recv_overlap.addr);
			packet_del(pk);
			if(((socket_*)d)->status & SOCKET_CLOSE)
				return;
		}
	}
	PostRecv(d);
}
bool ClientSession::OnConnect(SOCKADDR_IN* addr)
{
	//TODO: 이 영역 lock으로 보호 할 것
	FastSpinlockGuard tempLock(mLock);

	CRASH_ASSERT(LThreadType == THREAD_MAIN_ACCEPT);

	/// make socket non-blocking
	u_long arg = 1 ;
	ioctlsocket(mSocket, FIONBIO, &arg) ;

	/// turn off nagle
	int opt = 1 ;
	setsockopt(mSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof(int)) ;

	opt = 0;
	if (SOCKET_ERROR == setsockopt(mSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&opt, sizeof(int)) )
	{
		printf_s("[DEBUG] SO_RCVBUF change error: %d\n", GetLastError()) ;
		return false;
	}
	
	HANDLE handle = CreateIoCompletionPort(
		(HANDLE)mSocket,
		GIocpManager->GetCompletionPort(),
		(ULONG_PTR)this,
		0
		);
		
		//TODO: 여기에서 CreateIoCompletionPort((HANDLE)mSocket, ...);사용하여 연결할 것

	if (handle != GIocpManager->GetCompletionPort())
	{
		printf_s("[DEBUG] CreateIoCompletionPort error: %d\n", GetLastError());
		return false;
	}

	memcpy(&mClientAddr, addr, sizeof(SOCKADDR_IN));
	mConnected = true ;

	printf_s("[DEBUG] Client Connected: IP=%s, PORT=%d\n", inet_ntoa(mClientAddr.sin_addr), ntohs(mClientAddr.sin_port));

	GSessionManager->IncreaseConnectionCount();

	return PostRecv() ;
}
Esempio n. 22
0
void ProactorService::open( ACE_HANDLE h, ACE_Message_Block& MessageBlock )
{
	this->handle(h);	

	if (this->m_AsyncReader.open(*this) != 0 || this->m_AsyncWriter.open(*this) != 0)
	{
		delete this;
		return;
	}
	
	m_pTimerLock = new InterlockedValue();
	m_pTimerLock->Release();

	m_bServiceCloseFlag = false;

	if (g_currentSessionCnt > GetEngine()->GetMaxUserAccept())
	{
		if (this->handle() != ACE_INVALID_HANDLE)
			ACE_OS::closesocket(this->handle());

		this->handle(ACE_INVALID_HANDLE);

		delete this;
		return;
	}

	m_serial = ProactorServiceManagerSinglton::instance()->Register(this);	

	if (m_serial == INVALID_ID)
	{
		if (this->handle() != ACE_INVALID_HANDLE)
			ACE_OS::closesocket(this->handle());

		this->handle(ACE_INVALID_HANDLE);
		
		delete this;
		return;
	}

	RegisterTimer();

	ISession::OnConnect(this->m_serial, m_sessionDesc);

	PostRecv();
}
Esempio n. 23
0
void Server::AddClient(Client* client)
{
    assert(client);

    // The socket sAcceptSocket does not inherit the properties of the socket associated with
    // sListenSocket parameter until SO_UPDATE_ACCEPT_CONTEXT is set on the socket.
    if (setsockopt(client->GetSocket(), SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
                   reinterpret_cast<const char*>(&m_listenSocket),
                   sizeof(m_listenSocket)) == SOCKET_ERROR)
    {
        ERROR_CODE(WSAGetLastError(), "setsockopt() for AcceptEx() failed.");

        RemoveClient(client);
    }
    else
    {
        client->SetState(Client::ACCEPTED);

        // Connect the socket to IOCP
        TP_IO* pTPIO = CreateThreadpoolIo(reinterpret_cast<HANDLE>(client->GetSocket()),
                                          Server::IoCompletionCallback, NULL, NULL);
        if (pTPIO == NULL)
        {
            ERROR_CODE(GetLastError(), "CreateThreadpoolIo failed for a client.");

            RemoveClient(client);
        }
        else
        {
            std::string ip;
            u_short port = 0;
            Network::GetRemoteAddress(client->GetSocket(), ip, port);
            TRACE("[%d] Accept succeeded. client address : ip[%s], port[%d]", GetCurrentThreadId(),
                  ip.c_str(), port);

            client->SetTPIO(pTPIO);

            EnterCriticalSection(&m_CSForClients);
            m_Clients.push_back(client);
            LeaveCriticalSection(&m_CSForClients);

            PostRecv(client);
        }
    }
}
bool ClientSession::OnConnect( SOCKADDR_IN* addr )
{
	memcpy( &m_ClientAddr, addr, sizeof( SOCKADDR_IN ) );

	/// 소켓을 넌블러킹으로 바꾸고
	u_long arg = 1;
	ioctlsocket( m_Socket, FIONBIO, &arg );

	/// nagle 알고리즘 끄기
	int opt = 1;
	setsockopt( m_Socket, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof( int ) );

	printf( "[DEBUG] Client Connected: IP=%s, PORT=%d\n", inet_ntoa( m_ClientAddr.sin_addr ), ntohs( m_ClientAddr.sin_port ) );

	m_Connected = true;

	return PostRecv();
}
Esempio n. 25
0
void ProactorService::handle_read_stream( const ACE_Asynch_Read_Stream::Result& result )
{
	ACE_Message_Block& block = result.message_block();
	if (!result.success() || result.bytes_transferred() == 0)
	{
		block.release();
		ReserveClose();
	}
	else
	{
		if (false == ISession::OnReceive(block.rd_ptr(), (unsigned short)block.length(), m_sessionDesc))
		{
			block.release();
			ReserveClose();
			return;
		}

		PostRecv();
	}
}
Esempio n. 26
0
void ProactorService::handle_read_stream( const ACE_Asynch_Read_Stream::Result& Result )
{
	ACE_Message_Block& Block = Result.message_block();
	if(!Result.success() || Result.bytes_transferred() == 0)
	{
		Block.release();
		ReserveClose();
	}
	else
	{
		if(false == ISession::OnReceive(Block.rd_ptr(), Block.length()))
		{
			Block.release();
			ReserveClose();
			return;
		}

		PostRecv();
	}
}
Esempio n. 27
0
//-----------------------------------------------------------------------------------
//		Purpose	:
//		Return	:
//-----------------------------------------------------------------------------------
// Called by Worker TH ( IOCP )
//-----------------------------------------------------------------------------------
int CNtlConnection::CompleteConnect(DWORD dwTransferedBytes)
{
	FUNCTION_BEGIN();

	UNREFERENCED_PARAMETER( dwTransferedBytes );

	m_socket.GetPeerAddr( m_remoteAddr );
	m_socket.GetLocalAddr( m_localAddr );
	m_bConnected = true;

	int rc = m_pNetworkRef->Associate( this, true );
	if( NTL_SUCCESS != rc )
	{
		NTL_LOGDL( LOG_NETWORK, "Session[%X] CompleteConnect Error[%d:%s]", this, rc, NtlGetErrorMessage(rc) );
		return rc;
	}


	SetStatus( STATUS_ACTIVE );
	m_dwConnectTime = GetTickCount();


	m_pConnectorRef->OnConnected();


	m_pNetworkRef->PostNetEventMessage( (WPARAM)NETEVENT_CONNECT, (LPARAM)this );	


	rc = PostRecv();
	if( NTL_SUCCESS != rc )
	{
		return rc;
	}



	//NTL_PRINT(PRINT_SYSTEM, "Session[%X]\tCompleteConnect Called Local[%s:%u] Remote[%s:%u]", pSession, GetLocalIP(), GetLocalPort(),	GetRemoteIP(), GetRemotePort() );


	return NTL_SUCCESS;
}
Esempio n. 28
0
void NetSocket::OnRecv(NetCompletionOP* recvOP, DWORD bytesTransfered)
{
    REFLIB_ASSERT_RETURN_IF_FAILED(recvOP, "NetIoBuffer is null");

    NetIoBuffer *ioBuffer = reinterpret_cast<NetIoBuffer*>(recvOP);
    MemoryBlock* buffer;

    if (buffer = ioBuffer->PopData())
    {
        OnRecvData(buffer->GetData(), bytesTransfered);
    }
    else
    {
        Disconnect(NetCloseType::NET_CTYPE_SYSTEM);
    }

    delete ioBuffer;
    _netStatus.fetch_and(~NET_STATUS_RECV_PENDING);

    PostRecv();
}
Esempio n. 29
0
//接数数据
int  CYCTReaderInterface::SendReaderCommand(char *ComPort,unsigned char Cmd,unsigned char *SendData,
											unsigned  char SendDataLen,unsigned char *RetCode,
											unsigned char *RecvData,unsigned char* RecvDataLen)
{
	char sCmd[256],sResp[256];
	int  nCmdLen=0;

	memset(sCmd,0,sizeof sCmd);
	memset(sResp,0,sizeof sResp);
	if( !m_bComStatus )
	{
		if( !CPU_Open(m_sCom,57600) )
		{
			RetCode[0]=0x4F;
			return 1;
		}
	}
	sCmd[0]=(char)0xBA;
	sCmd[1]=(char)(2+SendDataLen);
	sCmd[2]=Cmd;
	memcpy(sCmd+3,SendData,SendDataLen);
	nCmdLen=3+SendDataLen;
	sCmd[nCmdLen]=XOR((byte*)sCmd,nCmdLen);
	nCmdLen++;
	if( !PostSend(sCmd,nCmdLen,2000) )
	{
		return SEND_DATA_ERROR;
	}
	Sleep(80);
	if( !PostRecv(sResp,sizeof(sResp),2000) )
	{
		return RECV_DATA_ERROR;
	}
	*RetCode=sResp[3];
	*RecvDataLen=sResp[1]-3;	
	if(*RecvDataLen>0) memcpy(RecvData,sResp+4,*RecvDataLen);	
	return 0;
}
Esempio n. 30
0
bool ClientSession::OnConnect(SOCKADDR_IN* addr)
{
	memcpy( &mClientAddr, addr, sizeof(SOCKADDR_IN) );

	/// 소켓을 넌블러킹으로 바꾸고

	u_long arg = 1 ;
	::ioctlsocket( mSocket, FIONBIO, &arg );

	/// nagle 알고리즘 끄기
	int opt = 1;
	::setsockopt( mSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof(int) );

	printf( "[DEBUG] Client Connected: IP=%s, PORT=%d\n", inet_ntoa(mClientAddr.sin_addr), ntohs(mClientAddr.sin_port) );

	/// 패킷 핸들링
	mPacketHandler[PKT_CS_LOGIN] = ClientLoginPacket;
	mPacketHandler[PKT_CS_KEYSTATE] = ClientKeyStatePacket;
	mPacketHandler[PKT_CS_MOUSEANGLE] = ClientMouseAnglePacket;

	mConnected = true;

	return PostRecv();
}