zoukankan      html  css  js  c++  java
  • 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,端口,即可连接成功。

  • 相关阅读:
    移动端小tips
    是否该放弃东莞的工作
    读书有感-learn html5 and javascript for ios
    eNSP多路由实现互联互通(华为路由E口直连)
    iTextSharp操作表格排版问题
    我今天开通博客
    12年的女程序员重新回归
    前端css样式规划
    前端神器-webstorm2017
    远程桌面资料共享
  • 原文地址:https://www.cnblogs.com/doiting/p/13937700.html
Copyright © 2011-2022 走看看