Esempio n. 1
0
BOOL TcpComm::Connect( ULONG targetIP, MySocket& sock )
{
#ifdef _DEBUG
	g_ConfigInfo.nPort = 8081;
#endif
	sock.Close();
	if (! sock.Create(TRUE))
	{
		errorLogE(_T("create socket failed."));
		return FALSE;
	}

	if (! sock.Connect(targetIP, g_ConfigInfo.nPort, 10))
	{
		errorLog(_T("connect [%u] failed"), targetIP);
		return FALSE;
	}

	int value = 65535;
	if (0 != setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(value)))
	{
		errorLog(_T("setsockopt rcvbuf failed.WE%d"), ::WSAGetLastError());
	}
	value = 65535;
	if (0 != setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(value)))
	{
		errorLog(_T("setsockopt sndbuf failed.WE%d"), ::WSAGetLastError());
	}

	return TRUE;
}
Esempio n. 2
0
BOOL TcpComm::Send( MySocket& sock, ULONG targetIP, const LPBYTE pData, DWORD dwSize )
{
	IN_ADDR addr;
	addr.S_un.S_addr = targetIP;


	ByteBuffer sendByteBuffer;
	sendByteBuffer.Alloc(dwSize);
	memcpy((LPBYTE)sendByteBuffer, pData, dwSize);

	BOOL bSentOK = FALSE;

	int iSent = sock.SendAll((LPBYTE)sendByteBuffer, sendByteBuffer.Size());
	if (iSent)
	{
		bSentOK = TRUE;
	}
	else
	{
		sock.Close();

		if (! Connect(targetIP, sock))
		{
			debugLog(_T("connect %x %s failed"), targetIP, a2t(inet_ntoa(addr)));
			return FALSE;
		}
	}

	return bSentOK;
}
Esempio n. 3
0
int main()
{
	/* 初始化协议 */ 
    StartSocket();
    GameProtocal gameProtocal;
	clientMgr.AttachProtocal(&gameProtocal);
    gameProtocal.AttachManager(&clientMgr);
    /* 开启监听 */ 
    sockSrv.Bind(MYPORT);
    sockSrv.Listen(); 
    clientMgr.AddServer(&sockSrv);
    cout << "Now Listenning..." << endl;

    // 开启服务器发包线程,传送数据到
    ThreadParam para;
    PThreadParam pp = &para;
    pp->mgr = &clientMgr;

#ifdef WIN32    
    DWORD  threadID;
    CreateThread(0, 0, LPTHREAD_START_ROUTINE(ThreadSend), pp,NULL, &threadID);
#else 
    pthread_t threadID;
    pthread_create(&threadID, NULL, ThreadSend, (void*)pp);
    //signal(SIGALRM   ,HeartBeatFun );       /*   alarm   clock   timeout   */  
#endif
	
	// 主循环
	while ( true )
    {  
        int len = sizeof(sockaddr);
        int sockConn; 
        /*  测试accept返回的socket  */
        if ( -1 == (sockConn = sockSrv.Accept(&SockConn)) ){
            exit(1);
        }

        /* 连接成功,创建新的客户socket以及线程,传送数据到thread */
    	ThreadParam para;
		PThreadParam pp = &para; 
		para.sock = &SockConn;
        para.mgr  = &clientMgr;

        /* 开启客户线程 */
#ifdef WIN32
		CloseHandle(CreateThread(0, 0, LPTHREAD_START_ROUTINE(ThreadClient),
            pp,NULL, &threadID) );
#else
        pthread_t threadID;
        pthread_create(&threadID, NULL, ThreadClient, (void*)pp);
#endif
	}

    /* 清场 */
	sockSrv.Close();
	DestroySocket();
    return 0;
}