在C6748上使用C:
tindk_2_23_02_03packagestindktoolsconsoleconecho.c 中函数EchoTcp来连接服务端发送数据,函数代码如下:
/*---------------------------------------------------------------------- */
/* EchoTcp() */
/* Test ECHO with a TCP socket */
/*---------------------------------------------------------------------- */
static void EchoTcp( IPN IPAddr )
[
SOCKET s;
struct sockaddr_in sin1;
int test,i;
char *pBuf = 0;
struct timeval timeout;
ConPrintf("n== Start TCP Echo Client Test ==n");
/* Create test socket */
s = socket(AF_INET, SOCK_STREAMNC, IPPROTO_TCP);
if( s == INVALID_SOCKET )
[
ConPrintf("failed socket create (%d)n",fdError());
goto leave;
]
/* Prepare address for connect */
bzero( &sin1, sizeof(struct sockaddr_in) );
sin1.sin_family = AF_INET;
sin1.sin_len = sizeof( sin1 );
sin1.sin_addr.s_addr = IPAddr;
sin1.sin_port = htons(7);
/* Configure our timeout to be 5 seconds */
timeout.tv_sec = 5;
timeout.tv_usec = 0;
setsockopt( s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof( timeout ) );
setsockopt( s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof( timeout ) );
/* Connect socket */
if ( connect( s, (PSA) &sin1, sizeof(sin1) ) < 0 )
[
ConPrintf("failed connect (%d)n",fdError());
goto leave;
]
/* Allocate a working buffer */
if( !(pBuf = mmBulkAlloc( 12288 )) )
[
ConPrintf("failed temp buffer allocationn");
goto leave;
]
/* Start Test */
for( test=48; test<=12288; test*=2 )
[
/* Fill buffer with a test pattern */
for(i=0; i
*(pBuf+i) = (char)i;
/* Send the buffer */
ConPrintf("Sending %d bytes ... ",test);
if( send( s, pBuf, test, 0 ) < 0 )
[
ConPrintf("send failed (%d)n",fdError());
break;
]
/* Clear the test pattern */
mmZeroInit( pBuf, (uint)test );
/* Try and receive the test pattern back */
ConPrintf("receive ... ");
i = recv( s, pBuf, test, MSG_WAITALL );
if( i < 0 )
[
ConPrintf("recv failed (%d)n",fdError());
break;
]
/* Verify reception size */
if( i != test )
[
ConPrintf("received %d (not %d) bytesn",i,test);
break;
]
/* Verify the test pattern */
ConPrintf("verify ... ");
for(i=0; i
if( *(pBuf+i) != (char)i )
[
ConPrintf("verify failed at byte %dn",i);
break;
]
if( i==test )
ConPrintf("passedn");
]
leave:
if( pBuf )
mmBulkFree( pBuf );
if( s != INVALID_SOCKET )
fdClose( s );
ConPrintf("== End TCP Echo Client Test ==nn");
]
多次运行上述程序进行客户端(
开发板)连接服务端(PC端)并发送数据,发现以下现象:
1 客户端使用的端口号一直是57384,可以通过设置来实现客户端端口号是随机变化的吗?
这个现象我用windows上vc环境的socket编程做过测试,其多次运行客户端实际使用的端口都是变化的,打印信息如下:
【Receive from 192.168.2.100 : 2713】:hello 0
【Receive from 192.168.2.100 : 2736】:hello 0
【Receive from 192.168.2.100 : 2742】:hello 0
【Receive from 192.168.2.100 : 2744】:hello 1
【Receive from 192.168.2.100 : 2745】:hello 2
2 EchoTcp函数在执行connect操作时,大部分情况下会出现几秒的停顿与延时才能完成连接,请问这个和上面描述的客户端端口号固定不变有联系吗?
测试环境的服务器使用的是网络调试助手工具,服务端一旦listen后就没有再做其他任何操作;
if ( connect( s, (PSA) &sin1, sizeof(sin1) ) < 0 )
[
ConPrintf("failed connect (%d)n",fdError());
goto leave;
]
0