本节我们使用开发板建立一个 tcp 客户端,再去连接指定地址和端口的 tcp 服务端并进行数据通信。打开宏定义 DEMO_SOCKET_CLIENT_SERVER、DEMO_CONNECT_NET;
在开发板连网成功后,创建TCP 服务连接。
static int create_socket_server(int port)
{
char sock_rx[DEMO_SOCK_BUF_SIZE] = {0};
struct sockaddr_in server_addr; // server address information
struct sockaddr_in client_addr; // connector\'s address information
socklen_t sin_size;
int ret;
while(1)
{
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("create socket fail,errno :%d\\n",errno);
break;
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = ((u32) 0x00000000UL);
memset(server_addr.sin_zero, \'\\0\', sizeof(server_addr.sin_zero));
if (bind(server_fd, (struct sockaddr *) &server_addr,
sizeof(server_addr)) != 0)
{
printf("bind fail, errno:%d\\n",errno);
break;
}
if (listen(server_fd, 1) != 0)
{
printf("listen fail,errno:%d\\n",errno);
break;
}
printf("listen port %d\\n", port);
sin_size = sizeof(client_addr);
new_fd = accept(server_fd, (struct sockaddr *) &client_addr,
&sin_size);
printf("accept newfd = %d\\n",new_fd);
if (new_fd < 0)
{
printf("accept fail,errno:%d\\n",errno);
break;
}
while (1)
{
memset(sock_rx, 0, DEMO_SOCK_BUF_SIZE);
ret = recv(new_fd, sock_rx, sizeof(sock_rx)-1, 0);
if(ret == 0)
{
printf("connection disconnect\\n");
break;
}
else if(ret < 0)
{
printf("receive fail errno:%d\\n",errno);
break;
}
else
{
sock_rx[ret] = 0;
printf("\\nReceive %d bytes from %s\\n", ret, inet_ntoa(client_addr.sin_addr.s_addr));
printf("%s\\n",sock_rx);
ret = send(new_fd, sock_tx, strlen(sock_tx), 0);
if (ret < 0)
{
printf("Error occured during sending,errno:%d\\n",errno);
break;
}
}
}
if(new_fd != -1)
{
printf("shutting down socket and restaring...\\n");
shutdown(new_fd,0);
closesocket(new_fd);
}
}
return 0;
}
程序编译并下载到开发板,串口输入指令指定路由器名称,密码,TCP端口,如:t-server("@snail","ss559550",8080,),可以看到连接网络后分配到开发板 tcp服务器的ip地址192.168.2.107。
在 PC 上建立一个 tcp client,设置好要连接的TCP服务器IP,端口,即可连接成功。