⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatinet.cpp

📁 一个聊天的软件
💻 CPP
📖 第 1 页 / 共 2 页
字号:
// ----------------------------------------------------------------------------
// CChatInet::DisconnectL()
// Disconnects from the remote machine.
// ----------------------------------------------------------------------------
//
void CChatInet::DisconnectL()
    {
    if ( ( State() == EConnected )||( State() == ESendingMessage ) )
        {
        DisconnectFromServerL();
        SetState( EDisconnecting );
        }
    else
        {
        HBufC* errNoConn = StringLoader::LoadLC ( R_CHAT_ERR_NO_CONN );
        iLog.LogL( *errNoConn );
        CleanupStack::PopAndDestroy( errNoConn );
        User::Leave( KErrDisconnected );
        }
    }

// ----------------------------------------------------------------------------
// CChatInet::DisconnectFromServerL()
// Disconnects from the service
// ----------------------------------------------------------------------------
//
void CChatInet::DisconnectFromServerL()
    {
    // Terminate all operations
    iSocket.CancelAll();
    Cancel();

    HBufC* strReleasingConn = StringLoader
        ::LoadLC ( R_CHAT_STR_RELEASING_CONN );
    iLog.LogL( *strReleasingConn );
    CleanupStack::PopAndDestroy( strReleasingConn );
    iSocket.Shutdown( RSocket::ENormal, iStatus );
    SetActive();
    }

// ----------------------------------------------------------------------------
// CChatInet::ConnectToServerL()
// Connect to the server.
// ----------------------------------------------------------------------------
//
void CChatInet::ConnectToServerL( const TDesC& aAddress )
    {
    HBufC* strConnecting = StringLoader
        ::LoadLC ( R_CHAT_STR_CONNECTING );
    iLog.LogL( *strConnecting );
    CleanupStack::PopAndDestroy( strConnecting );
    
    TInetAddr addr;
  if ( addr.Input( aAddress ) == KErrNone )
        {
        // server name is already a valid ip address
        ConnectL( addr.Address() );
        }
    else 
        {
        // Initiate DNS
        User::LeaveIfError( iResolver.Open( iSocketServer,
                                            KAfInet,
                                            KProtocolInetTcp ) );
        // DNS request for name resolution
        iResolver.GetByName( aAddress, iNameEntry, iStatus );
        
        TRequestStatus waitStatus = KRequestPending;
        RTimer timer;
        timer.CreateLocal();
    
        timer.After( waitStatus, KChatTimeOut );
     
        User::WaitForRequest( iStatus, waitStatus );
        
        if ( iStatus == KRequestPending )
            {
            iResolver.Cancel();
            
            User::WaitForRequest( iStatus );
            iResolver.Close();
            // Operation did not complete in time.
            HBufC* strConnecting = StringLoader
                ::LoadLC ( R_CHAT_ERR_TIMEOUT );
            iLog.LogL( *strConnecting );
            CleanupStack::PopAndDestroy( strConnecting );
            SetState( EDisconnected );
            timer.Close();
            User::Leave( KErrTimedOut );

            }
        else
            {
            // DNS look up successful
        	iNameRecord = iNameEntry();
        	TBuf<KIpAddressLen> ipAddr;
        	TInetAddr::Cast( iNameRecord.iAddr ).Output( ipAddr );
        	ConnectL( TInetAddr::Cast( iNameRecord.iAddr ).Address() );
        	
            timer.Cancel();
            User::WaitForRequest( waitStatus );
            timer.Close();
            iResolver.Close();
            }

      }

  #ifdef __WINS__
      User::After( 1 );     // Fix to allow emulator client to connect to server
  #endif
  
    SetState( EGettingConnection );

    SetActive();
    }


// -----------------------------------------------------------------------------
// CChatInet::ConnectL()
// Initiates a connect operation on a socket.
// -----------------------------------------------------------------------------
//
void CChatInet::ConnectL( TUint32 aAddr )
    {
    iActiveSocket = &iSocket;
    iAddress.SetPort( iPort );
    iAddress.SetAddress( aAddr );
    iAddress.SetFamily( KAfInet );
        
    // Open a TCP socket
    User::LeaveIfError( iSocket.Open( iSocketServer,
        KAfInet,
        KSockStream,
        KProtocolInetTcp ) );

    // Initiate socket connection
    iSocket.Connect( iAddress, iStatus );
    }


// ----------------------------------------------------------------------------
// CChatInet::SendMessageL()
// Send a message to a service on a remote machine.
// ----------------------------------------------------------------------------
//
void CChatInet::SendMessageL( const TDesC& aText )
    {
    if ( State() != EConnected )
        {
        User::Leave( KErrDisconnected );
        }

    // stop reading socket
    if ( iActiveSocket )
        {
        iActiveSocket->CancelRead();  
        }

    if ( IsActive() )
        {
        Cancel();
        }
      
    TBufC<KChatTextBufLength> message ( aText );
    SetState( ESendingMessage );
    HBufC* tempString = HBufC::NewL( message.Length() );
    tempString->Des().Copy( message );
    
    iMessage = HBufC8::NewL(tempString->Length());
    iMessage->Des().Copy( *tempString );
    
    // write message to socket
    if ( iActiveSocket )
        {
        iActiveSocket->Write( *iMessage, iStatus );
        }
    delete tempString;
    SetActive();
    }


// ----------------------------------------------------------------------------
// CChatInet::StartL()
// Starts the server.
// ----------------------------------------------------------------------------
//
void CChatInet::StartL()
    {
    if ( State() != EDisconnected )
        {
        User::Leave( KErrInUse );
        }
    
    User::LeaveIfError( iConnection.Open( iSocketServer, KAfInet) );
    
    User::LeaveIfError( iConnection.Start() );
      
    TInt result( 0 );
    
    result = iSocket.Open( iSocketServer, 
        KAfInet, 
        KSockStream, 
        KProtocolInetTcp );
      
    if ( result != KErrNone )
        {
        iSocketServer.Close();
        User::Leave( result ); 
        }

    TInetAddr addr;
    iAddress.SetPort( iPort );
    iAddress.SetFamily( KAfInet );

    // bind
    User::LeaveIfError( iSocket.Bind( iAddress ) );
    
    // listen
    User::LeaveIfError( iSocket.Listen( KListeningQueSize ) );

    // close old connection - if any
    iAcceptedSocket.Close();

    // Open abstract socket
    User::LeaveIfError( iAcceptedSocket.Open( iSocketServer ) );  
  
    iActiveSocket = &iAcceptedSocket;
  
    // Set the Active Object's State to Connecting indicated.
    SetState( EGettingConnection );

    iSocket.Accept( iAcceptedSocket, iStatus );

    SetServer( ETrue );

    // Set the Active Object Active again,
    SetActive();
   
    }


// ----------------------------------------------------------------------------
// CChatInet::Stop()
// Stops the server.
// ----------------------------------------------------------------------------
//
void CChatInet::Stop()
    {
    if ( State() != EDisconnected )
        {
        // Close() will wait forever for Read to complete
        if ( State() == EConnected )
            {
            if ( iActiveSocket )
                {
                iActiveSocket->CancelRead();
                }
            }
        iAcceptedSocket.Close();
        iSocket.Close();
        }
        SetState( EDisconnected );
    }

// ----------------------------------------------------------------------------
// CChatInet::RequestData()
// Request data from the client.
// ----------------------------------------------------------------------------
//
void CChatInet::RequestData()
    {
    if ( iActiveSocket )
        {
        iActiveSocket->RecvOneOrMore( iBuffer, 0, iStatus, iLen );
        }
    SetActive();
    }


// End of File

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -