C基于客户端的通信实例

运行环境liunx 

需求:客户端对服务器发送一个TCP连接,连接成功之后发送数据并接收返回数据

代码如下:

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main( int argc, char* argv[] ) {
    if( argc <= 2 )
    {
        printf( "usage: %s ip_address port_number\n", basename( argv[0] ) );
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi( argv[2] );

    struct sockaddr_in server_address;
    bzero( &server_address, sizeof( server_address ) );
    server_address.sin_family = AF_INET;
    inet_pton( AF_INET, ip, &server_address.sin_addr );
    server_address.sin_port = htons( port );

    int sockfdclient = socket( PF_INET, SOCK_STREAM, 0 );
    assert( sockfdclient >= 0 );
    if ( connect( sockfdclient, ( struct sockaddr* )&server_address, sizeof( server_address ) ) < 0 )
    {
        printf( "connection failed\n" );
    exit(-1);
    }
    
    while(1) {
        const char* normal_data = "123";
        int iSend = send( sockfdclient, normal_data, strlen( normal_data ), 0 );
        if(iSend == -1){  
            printf("send failed");  
        }  
    
        char buffer[1024];
        memset( buffer,'\0', 1024);
        recv(sockfdclient, buffer, sizeof(buffer), 0);
        int count = atoi(buffer);
    printf("%d",count);
    
    if( count == 0) 
        break;

    usleep(1000000);
    }
    close( sockfdclient); 
    return 0;
}

运行g++ -o a a.c

posted @ 2016-12-23 18:08  Nancy26  阅读(202)  评论(0编辑  收藏