我想创建一个TCP服务器能够被多个客户端连接,所以程序做了如下尝试。
1)第一种方法:在TCP_peRForm_receive函数中,如果以函数的形式调用TCP_server_connect_handle,该TCP服务器能够被连接,且能够正常接发数据,但是仅限于一个Socket建立成功,如果第二个客户端想连接TCP服务器,能够连接成功,但是不能正常接发数据。
2)第二种方法:在TCP_perform_receive函数中,如果accept成功,我则建立一个线程,并把socket地址传到这个线程函数TCP_server_connect_handle中,结果是,客户端能连接成功,但是都不能正常接发数据,通过仿真器,我也确认了在TCP_server_connect_handle中,stcp_child这个Socket的地址接收成功啦。想不通为什么不能正常接发数据?
我知道要想建立TCP服务器被多个客户端相连,要用第二种方法,可是我想不通为什么不能正常接发数据,难道单纯传Socket地址不行吗?
void TCP_server_connect_handle(unsigned int UArg0,unsigned int UArg1)
{
char *pBuf;
HANDLE hBuffer;
int32_t bytes;
// SOCKET stcp_child;
// printf("TCP_server_connect_handle: %d,%d \n",UArg0,UArg1);
stcp_child =(SOCKET*) UArg1;
while(1)
{
// There is data available on the active connection 接收客户端发送过来的数据
bytes = (int)recvnc(stcp_child, (void **)&pBuf, 0, &hBuffer);
// if(bytes > 0)
// {
bytes = send(stcp_child, pBuf, (int)TCP_SERVER_BUFSIZE, 0 );
if(bytes < 0)
{
printf("FaiLED tcp server send!\n");
}
bytes = 0;
// recvncfree(hBuffer);
// }
TaskSleep(20);
}
}
static void TCP_perform_receive() //做为TCP_server模式并接收TCP_client的接入,接收数据并统计接收速率
{
int32_t size;
struct sockaddr_in sin1;
int8_t iClientNum = 0;
SOCK *ps = (SOCK *)stcp_child;
Task_Params TaskParams;
char *pBuf;
HANDLE hBuffer;
int32_t bytes;
printf("TCP server Task started\n");
/* Allocate the file environment for this task */
fdOpenSession(TaskSelf());
/* Create the main TCP listen socket 绑定IP和网络端口*/
stcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //SOCK_STREAM SOCK_STREAMNC
if(stcp == INVALID_SOCKET)
{
printf( "Fail socket, %d\n", fdError());
goto leave;
}
/* Set Port = 10001, IP address = IPAddrSend */
bzero(&sin1, sizeof(struct sockaddr_in));
sin1.sin_family = AF_INET;
sin1.sin_len = sizeof(sin1);
sin1.sin_addr.s_addr = inet_addr(LocalIPAddr);
sin1.sin_port = htons(TCP_SERVER_PORT);
if(bind(stcp, (struct sockaddr *)&sin1, sizeof(sin1)) < 0)
{
fdClose( stcp);
stcp = INVALID_SOCKET;
printf("Fail to bind socket, %d\n", fdError());
goto leave;
}
/* If the socket is bound and TCP, start listening */
if(listen(stcp, 20) < 0)
{
fdClose( stcp );
printf("Fail to listen on socket, %d\n", fdError());
stcp = INVALID_SOCKET;
goto leave;
}
while(1)
{
size = sizeof(sin1);
bzero( &sin1, sizeof(struct sockaddr_in) );
stcp_child = accept(stcp, (PSA)&sin1, &size); //阻塞等待客户端连接
ps = (SOCK *)stcp_child;
if(stcp_child == INVALID_SOCKET)
{
printf("Failed accept due to error: %d \n", fdError());
goto leave;
}
else
{
printf("successfully got a connection from: %d \n",ps->FIP);
//创建多线程
Task_Params_init(&TaskParams);
TaskParams.priority = 8;
TaskParams.stackSize = 0x1000;
TaskParams.arg0 = ps->FIP;
TaskParams.arg1 = *(xdc_UArg*)&stcp_child;
Task_create((Task_FuncPtr)TCP_server_connect_handle, &TaskParams, NULL);
// TCP_server_connect_handle(ps->FIP,0);
}
}
leave:
if(stcp_child != INVALID_SOCKET)
fdClose(stcp_child);
if(stcp != INVALID_SOCKET)
fdClose(stcp);
TaskSleep(2000);
fdCloseSession(TaskSelf());
TaskDestroy(TaskSelf());
}
|