文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>TCP socket Client

TCP socket Client

时间:2010-10-28  来源:xqzhao206

static int Tcp1SocketCollectdata(unsigned char * cmd, int cmd_len,
                                 unsigned char * data, int data_len)
{
    int sock;
    struct sockaddr_in server;
    int received = 0;
    
    /* Create the TCP socket */
    if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    {
        printf("Tcp1SocketCollectdata create socket failed!\n");
        return 0;
    }
    struct timeval tv;
    tv.tv_sec = 3; /* 3 Secs Timeout */
    tv.tv_usec = 0; // Not init'ing this can cause strange errors

    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
    /* Construct the server sockaddr_in structure */
    memset(&server, 0, sizeof(server)); /* Clear struct */
    server.sin_family = AF_INET; /* Internet/IP */
    server.sin_addr.s_addr = inet_addr("192.168.0.2"); /* IP address */
    server.sin_port = htons(6666); /* server port */
    /* Establish connection */
    if(connect(sock,
                (struct sockaddr *) &server,
                sizeof(server)) < 0)
    {
        printf("Tcp1SocketCollectdata connect socket failed!\n");

        close(sock);
        return 0;
    }
    if(send(sock, cmd, cmd_len, 0) != cmd_len) {
        printf("Tcp1SocketCollectdata sent cmd failed!\n");

        close(sock);
        return 0;
    }
    if((received = recv(sock, data, data_len, 0)) < 1) {
        printf("Tcp1SocketCollectdata receive failed!\n");
        close(sock);

        return 0;
    }
    // 校验
    printf("Tcp1SocketCollectdata received %d bytes\n", received);
    close(sock);

    return 0;
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载