ZHCU938C May 2018 – January 2021 CC3100 , CC3100MOD , CC3200 , CC3200MOD
与 TCP 客户端不同,TCP 服务器必须在进行通信之前确定几件事情。
SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
#define PORT_NUM 5001
SlSockAddrIn_t LocalAddr;
LocalAddr.sin_family = SL_AF_INET;
LocalAddr.sin_port = sl_Htons(PORT_NUM);
LocalAddr.sin_addr.s_addr = 0;
Status = sl_Bind(SockID, (SLSockAdd_t *) &LocalAddr, sizeof(SlSockAddrIn_t));
Status = sl_Listen(SockID, 0);
连接成功后,会返回一个新的套接字处理程序 newSockID,然后将该标识用于将来的通信。
long nonBlocking = 1;
int newSockID;
Status = sl_SetSockOpt (SockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &nonBlocking, sizeof(nonBlocking));
while( newSockID < 0 )
{
newSockID = sl_Accept(SockID, ( struct SlSockAddr_t
*) &Addr, (SlSocklen_t*) &AddrSize) ;
if( newSockID == SL_EAGAIN )
{
/* 等待 1 毫秒 */
Delay(1);
}
else if( newSockID < 0 )
{
return -1;
}
}
#define BUF_SIZE 1400
char SendBuf[BUF_SIZE];
/* 将数据写入缓冲区*/
<write buffer action>
Status = sl_Send(newSockID, SendBuf, BUF_SIZE, 0 );
char RecvBuf[BUF_SIZE];
Status = sl_Recv(newSockID, RecvBuf, BUF_SIZE, 0);
sl_Close(newSockID);
sl_Close(SockID);