client端:
#define TCP_PORT 5001
#define TCP_BUF 1500
int sock = -1;
struct sockaddr_in server;
static void tcp_client_main()
{
int ret;
uint32_t *buffer = NULL;
int size = 0;
int sender_len;
buffer = malloc(TCP_BUF);
if (NULL == buffer)
goto tcp_exit;
memset(buffer,0x0,TCP_BUF);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
os_printf("err = %d.\n", errno);
server.sin_family = PF_INET;
server.sin_port = htons(TCP_PORT);
server.sin_addr.s_addr = inet_addr("192.168.0.1");
while (1){
ret = connect(sock, (struct sockaddr *)&server, sizeof(server));
if (ret < 0){
continue;
}
else{
break;
}
}
while(1){
size = recv(sock, buffer, TCP_BUF, 0);
if (size > 0){
os_printf("rcv server data, begin to write data.\n");
}
else{
close(sock);
sock = -1;
goto tcp_exit;
}
}
tcp_exit:
if (buffer){
free(buffer);
buffer = NULL;
}
if (sock >=0){
closesocket(sock);
sock = -1;
}
}
static void udp_server_main()
{
fd_set watchfd;
int buffer;
int send_len, size;
buffer = malloc(TCP_BUF);
if (NULL==buffer)
return;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0){
goto server_exit;
}
server.sin_family = PF_INET;
server.sin_port = htons(TCP_PORT);
server.sin_addr.s_addr = inet_addr("0.0.0.0");
if(bind(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) < 0){
goto server_exit;
}
if (listen(sock, 0) == -1){
goto server_exit;
}
while(1){
FD_ZERO(&watchfd);
FD_SET(sock, &watchfd);
ret = select(sock+1, &watchfd, NULL, NULL, NULL);
if (ret <= 0){
continue;
}
else{
if (FD_ISSER(sock, &watchfd)){
struct sockaddr_in cli_addr;
socklen_t cli_len = sizeof(cli_addr);
new_sockfd = accept(sock, (struct sockaddr *)&cli_addr, &cli_len);
if (new_sockfd <0){
break;
}
int opt =1;
set_sockopt(fd, SOL_SOCKET, SO_KEEPLIVE, &opt, sizeof(int));
opt=30;
set_sockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &opt, sizeof(int));
opt=1;
set_sockopt(fd, IPPROTO_TCP, SO_KEEPINTVL, &opt, sizeof(int));
opt=3;
set_sockopt(fd, IPPROTO_TCP, SO_KEEPCNT, &opt, sizeof(int));
break;
}
}
}
while(1){
size = recv(new_sockfd , buffer, TCP_BUF, 0,);
if (size > 0){
os_printf("rcv server data, begin to write data.\n");
}
else{
close(new_sockfd );
new_sockfd= -1;
goto server_exit;
}
}
server_exit:
if (buffer){
free(buffer);
buffer = NULL;
}
if (sock >=0){
closesocket(sock);
sock= -1;
}
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/yisi15/article/details/136043586