打印

根据官网的例程改写的基于NDK的TCP服务器

[复制链接]
1805|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
吃肉的考拉|  楼主 | 2015-8-27 14:05 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
因为自己对TCP/IP网络通信不了解,omapl138 这个片子刚接触,也没找到相关例程,只是看了些文字资料,根据自己的理解在钢网例程上改写的,自然根本调试不通。。。有木有大神帮帮忙
//---------------------------------------------------------------------
// Main Entry Point
//---------------------------------------------------------------------
int main()
{
    /* Start the BIOS 6 Scheduler */
        printf("entry main \n");
        BIOS_start ();
        printf("exit main \n");
}

//
// Main Thread
//
int StackTest()
{
        printf("entry StackTest \n");
    HANDLE   hCfg;
   // char     *hn = "tidsp";
    int      rc;
  //  uint     tmp;

    //
    // THIS MUST BE THE ABSOLUTE FIRST THING DONE IN AN APPLICATION!!
    //
    rc = NC_SystemOpen( NC_PRIORITY_LOW, NC_OPMODE_INTERRUPT );
    if( rc )
    {
        printf("NC_SystemOpen Failed (%d)\n",rc);
        for(;;);
    }

    // Print a banner
    printf(VerStr);

    //
    // We'll build a phony "default" configuration in this routine.
    // It will simulate having a default configuration stored in
    // non-volatile storage
    //

    // Create a new configuration
    hCfg = CfgNew();
    if( !hCfg )
    {
        printf("Unable to open configuration\n");
        goto main_exit;
    }
    /* Add our global hostname to hCfg (to be claimed in all connected domains) */
       CfgAddEntry(hCfg, CFGTAG_SYSINFO, CFGITEM_DHCP_HOSTNAME, 0,
                    strlen(HostName),
                    (UINT8 *)HostName, 0);
    //Add TCP config
    CI_IPNET NA;
    bzero(&NA,sizeof(NA));
    NA.IPAddr = inet_addr(LocalIPAddr);
    NA.IPMask = inet_addr(LocalIPMask);
    strcpy(NA.Domain,DomainName);
    NA.NetType = 0;
    CfgAddEntry(hCfg,CFGTAG_IPNET,1,0,
                            sizeof(CI_IPNET),
                            (UINT8 *)&NA,0);

    CI_ROUTE RT;
        bzero(&RT, sizeof(RT));
        RT.IPDestAddr = 0;
        RT.IPDestMask = 0;
        RT.IPGateAddr = inet_addr(GatewayIP);

        CfgAddEntry(hCfg, CFGTAG_ROUTE, 0, 0,
                        sizeof(CI_ROUTE), (UINT8 *)&RT, 0);
    // Add our global hostname (to be claimed in all connected domains)
   // CfgAddEntry( hCfg, CFGTAG_SYSINFO, CFGITEM_DHCP_HOSTNAME, 0,
    //             strlen(hn), (UINT8 *)hn, 0 );

    // Specify TELNET service
   /* {
        CI_SERVICE_TELNET telnet;

        bzero( &telnet, sizeof(telnet) );
        telnet.cisargs.IPAddr = INADDR_ANY;
        telnet.cisargs.pCbSrv = &ServiceReport;
        telnet.param.MaxCon   = 2;
        telnet.param.Callback = &ConsoleOpen;
        CfgAddEntry( hCfg, CFGTAG_SERVICE, CFGITEM_SERVICE_TELNET, 0,
                     sizeof(telnet), (UINT8 *)&telnet, 0 );
    }*/

    // Create RAM based WEB files for HTTP
    //AddWebFiles();

    // Specify HTTP service
  /*  {
        CI_SERVICE_HTTP http;

        bzero( &http, sizeof(http) );
        http.cisargs.IPAddr = INADDR_ANY;
        http.cisargs.pCbSrv = &ServiceReport;
        CfgAddEntry( hCfg, CFGTAG_SERVICE, CFGITEM_SERVICE_HTTP, 0,
                     sizeof(http), (UINT8 *)&http, 0 );
    }*/

    // We don't want to see debug messages less than WARNINGS
    /*tmp = DBG_WARN;
    CfgAddEntry( hCfg, CFGTAG_OS, CFGITEM_OS_DBGPRINTLEVEL,
                 CFG_ADDMODE_UNIQUE, sizeof(uint), (UINT8 *)&tmp, 0 );*/

    // Save the configuration to a linear buffer
    MainConfigSize = 0;
    CfgSave( hCfg, &MainConfigSize, 0 );
    printf("%d bytes required for save\n",MainConfigSize);
    if( MainConfigSize > sizeof( MainConfig ) )
        printf("FATAL: Config buffer too small\n");
    else
    {
        CfgSave( hCfg, &MainConfigSize, MainConfig );
        CfgFree( hCfg );

        // Now call what would really be the "boot" function
        NetBoot();
    }

    // Free the WEB files
  //  RemoveWebFiles();
    printf("exit StackTest1 \n");
    // Close the OS
main_exit:
    NC_SystemClose();
    printf("exit StackTest2 \n");
    return(0);

}


//---------------------------------------------------------------------
// Simulated Boot Entry Point
//---------------------------------------------------------------------
static void NetBoot()
{
        printf("entry NetBoot \n");
    HANDLE   hCfg;
    int      rc;

    //
    // Initialize the OS
    //
    // Note - we normally call NC_SystemOpen() here, but its already
    // been done in this simulation.
    //

    //
    // Boot the system using stored configuration
    //
    // We keep booting until the function returns 0. This allows
    // us to have a "reboot" command.
    //
    do
    {
        // Create a new configuration
        hCfg = CfgNew();
        if( !hCfg )
        {
            printf("Unable to open configuration\n");
            break;
        }

        // Load the configuration
        CfgLoad( hCfg, MainConfigSize, MainConfig );

        // Start the stack
        rc = NC_NetStart( hCfg, NetworkOpen, NetworkClose, NetworkIPAddr );

        // Delete Configuration
        CfgFree( hCfg );
    } while( rc > 0 );

    //
    // Close the OS
    //
    // Note - we normally call NC_SystemClose() here, but its done for
    // us in this simulation.
    //
    printf("exit NetBoot \n");
}

//
// System Task Code
//
static HANDLE hTCPServer =0;

#ifdef _INCLUDE_IPv6_CODE
static HANDLE hEcho6=0;
#endif

//
// NetworkOpen
//
// This function is called after the configuration has booted
//
static void NetworkOpen()
{
    // If we don't have any kind of IP in our configuration, we
    // do a "config by ping" function. The calling parameter is the
    // interface index to configure.
        printf("entry NetworkOpen \n");
    if( !MainConfigValid )
        hTCPServer = TaskCreate( TCPServer, "TCPServer", OS_TASKPRINORM, 0x1000, 1, 0, 0 );

    // Create our local servers
   /* hEcho = TaskCreate( echosrv, "EchoSrv", OS_TASKPRINORM, 0x1400, 0, 0, 0 );
    hData = TaskCreate( datasrv, "DataSrv", OS_TASKPRINORM, 0x1400, 0, 0, 0 );
    hNull = TaskCreate( nullsrv, "NullSrv", OS_TASKPRINORM, 0x1400, 0, 0, 0 );
    hOob  = TaskCreate( oobsrv,  "OobSrv", OS_TASKPRINORM, 0x1000, 0, 0, 0 );*/

#ifdef _INCLUDE_IPv6_CODE
    hEcho6 = TaskCreate( v6echosrv, "V6EchoSrv", OS_TASKPRINORM, 0x1400, 0, 0, 0 );
#endif
    printf("exit NetworkOpen \n");
}

//
// NetworkClose
//
// This function is called when the network is shutting down,
// or when it no longer has any IP addresses assigned to it.
//
static void NetworkClose()
{
        printf("entry NetworkClose \n");
    // Kill the GetIP task only if it did not complete
    if( hTCPServer )
        fdCloseSession( hTCPServer);
    /*fdCloseSession( hOob );
    fdCloseSession( hNull );
    fdCloseSession( hData );
    fdCloseSession( hEcho );*/

#ifdef _INCLUDE_IPv6_CODE
    fdCloseSession (hEcho6);
#endif

    // Kill any active console
    ConsoleClose();

    // If we opened NETCTRL as NC_PRIORITY_HIGH, we can't
    // kill our task threads until we've given them the
    // opportunity to shutdown. We do this by manually
    // setting our task priority to NC_PRIORITY_LOW.
    TaskSetPri( TaskSelf(), NC_PRIORITY_LOW );

    if( hTCPServer )
        TaskDestroy( hTCPServer );
    /*TaskDestroy( hOob );
    TaskDestroy( hNull );
    TaskDestroy( hData );
    TaskDestroy( hEcho );*/
    printf("exit NetworkClose \n");
}

//
// NetworkIPAddr
//
// This function is called whenever an IP address binding is
// added or removed from the system.
//
static void NetworkIPAddr( IPN IPAddr, uint IfIdx, uint fAdd )
{
        printf("entry NetworkIPAddr \n");
    IPN IPTmp;

    if( fAdd )
        printf("Network Added: ");
    else
        printf("Network Removed: ");

    // Print a message
    IPTmp = ntohl( IPAddr );
    printf("If-%d:%d.%d.%d.%d\n", IfIdx,
            (UINT8)(IPTmp>>24)&0xFF, (UINT8)(IPTmp>>16)&0xFF,
            (UINT8)(IPTmp>>8)&0xFF, (UINT8)IPTmp&0xFF );

    printf("exit NetworkIPAddr \n");
}

//
// Service Status Reports
//
// Here's a quick example of using service status updates
//
static char *TaskName[]  = { "Telnet","HTTP","NAT","DHCPS","DHCPC","DNS" };
static char *ReportStr[] = { "","Running","Updated","Complete","Fault" };
static char *StatusStr[] = { "Disabled","Waiting","IPTerm","Failed","Enabled" };
void ServiceReport( uint Item, uint Status, uint Report, HANDLE h )
{
        printf("entry ServiceReport \n");

        printf( "Service Status: %-9s: %-9s: %-9s: %03d\n",
            TaskName[Item-1], StatusStr[Status],
            ReportStr[Report/256], Report&0xFF );

        printf("exit ServiceReport \n");
}


//
// GetIP()
//
// Use ICMP ECHO request to get IP address
//
#define MAXPACKET 1000 // max packet size
static void TCPServer( uint IfIdx )
{
        printf("entry TCPServer \n");
    SOCKET   s,connectsocket;
    struct   sockaddr_in from;
    struct   sockaddr tcpaddr;
    char     *pBuf = 0;
    int      cc, len;
#if 0
    IPN      IPMe;
    ICMPHDR  *pIcHdr;
    IPHDR    *pIpHdr;
    int      IPHdrLen;
    CI_IPNET NA;
#endif
    // Allocate FDT
    fdOpenSession( TaskSelf() );

    // Allocate a working buffer
     if( !(pBuf = mmBulkAlloc( MAXPACKET )) )
         goto abort;


    // Create the ICMP Socket
    s = socket(AF_INET, SOCK_STREAM, 0);
    if( s == INVALID_SOCKET )
        goto abort;

    // Initialize the "from" address
    bzero( &from, sizeof(struct sockaddr_in));
    from.sin_family     = AF_INET;
    from.sin_port       = htons(DEFAULT_SOCKET_SERVER_PORT);
    from.sin_addr.s_addr     = 0xa214a8c6;
  //  from.sin_len        = sizeof( from );

    if(bind(s,(struct sockaddr *)&from,sizeof(from)) < 0)
    {

            printf("bind error\n");
            goto abort;
    }

    printf("socket port #%d\n",ntohs(from.sin_port));

    if(listen(s,5) == -1)
    printf("listen socket error\n");
    len = sizeof(struct sockaddr);
    printf("Accept Ready\n");

    while(1)
    {

#if 0
        fromlen = sizeof(from);
        printf("%d\n",fromlen);
        cc = (int)recvfrom( s, pBuf, MAXPACKET, 0, (PSA)&from, &fromlen );
        if( cc < 0 )
            goto abort;

        // Get header pointers
        pIpHdr   = (IPHDR *)pBuf;
        IPHdrLen = (pIpHdr->VerLen & 0xF) * 4;
        pIcHdr   = (ICMPHDR *)(pBuf+IPHdrLen);

        // Verify the ICMP type is ECHO request
        if( pIcHdr->Type != ICMP_ECHO )
            continue;

        // Use the destination address as our IP address
        IPMe = RdNet32( &pIpHdr->IPDst );

        // Add the IP to the configuration
        // Assume the netmask is 255.255.254.0
        bzero( &NA, sizeof(NA) );
        NA.IPAddr = IPMe;
        NA.IPMask = inet_addr("255.255.254.0");
        strcpy( NA.Domain, "default.net" );
        if( CfgAddEntry( 0, CFGTAG_IPNET, IfIdx, 0,
                         sizeof(CI_IPNET), (UINT8 *)&NA, 0 ) >= 0 )
            break;*/
#endif

            if((connectsocket=(SOCKET) accept(s,(struct sockaddr*)&tcpaddr,&len)) == INVALID_SOCKET)
                    {
                            printf("accept socket error\n");
                            continue;
                    }
            cc = recv(connectsocket,pBuf,MAXPACKET,0);
            pBuf[cc] = '\n';
            printf("recv msg from client:%s\n ",pBuf);
            fdClose(connectsocket);
    }

abort:
    hTCPServer = 0;

    printf("GetIP Closing\n");

    if( pBuf )
        mmBulkFree( pBuf );
    if( s != INVALID_SOCKET )
        fdClose( s );

    fdCloseSession( TaskSelf() );
    TaskExit();

    printf("exit GetIP2 \n");
}

相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

19

主题

58

帖子

0

粉丝