• W800 建立TCP服务器通信


    本节我们使用W800建立一个 tcp 客户端,再去连接指定地址和端口的 tcp 服务端并进行数据通信。打开宏定义 DEMO_SOCKET_CLIENT_SERVER、DEMO_CONNECT_NET;

    在w800连网成功后,创建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
    ",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, '', sizeof(server_addr.sin_zero));
    
    	if (bind(server_fd, (struct sockaddr *) &server_addr,
         	sizeof(server_addr)) != 0)
    	{
        	printf("bind fail, errno:%d
    ",errno);
    		break;
     	}
    	
    	if (listen(server_fd, 1) != 0)
    	{
        	printf("listen fail,errno:%d
    ",errno);
        	break;
    	}
    
    	printf("listen port %d
    ", port);
    	sin_size = sizeof(client_addr);
    	new_fd = accept(server_fd, (struct sockaddr *) &client_addr,
                       &sin_size);
        printf("accept newfd = %d
    ",new_fd);
    		
        if (new_fd < 0)
        {
              printf("accept fail,errno:%d
    ",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
    ");
    			break;
            }
    		else if(ret < 0)
    		{
    			printf("receive fail errno:%d
    ",errno);
    			break;
    		}
            else
            {     
            	 sock_rx[ret] = 0;
    			 printf("
    Receive %d bytes from %s
    ", ret, inet_ntoa(client_addr.sin_addr.s_addr));
    			 printf("%s
    ",sock_rx);
    			 ret = send(new_fd, sock_tx, strlen(sock_tx), 0);
    			 if (ret < 0)
    			 {
    			 	printf("Error occured during sending,errno:%d
    ",errno);
    				break;
    			 }
            }
     	}
    	if(new_fd != -1)
    	{
    		printf("shutting down socket and restaring...
    ");
    		shutdown(new_fd,0);
    		closesocket(new_fd);
    	}
    }
    return 0;
    

    }
    程序编译并下载到开发板,串口输入指令指定路由器名称,密码,TCP端口,如:t-server("@snail","ss559550",8080,),可以看到连接网络后分配到W800 tcp服务器的ip地址192.168.2.107。

    在 PC 上建立一个 tcp client,设置好要连接的TCP服务器IP,端口,即可连接成功。

  • 相关阅读:
    网络编程2018-4-23
    网络编程
    异常处理
    在Asp.net core使用配置Json创建动态目录树
    Asp.net Core中文转换成拼音
    解决Asp.Net core 控制台出现乱码的情况
    解决Asp.net Core中chtml文档中文乱码的问题
    取代Ajax.BeginForm的ajax使用方法
    将数据库模型放入到.Net Core的类库中
    如何使用Resource资源文件
  • 原文地址:https://www.cnblogs.com/doiting/p/13937700.html
Copyright © 2020-2023  润新知