C基于客户端的通信实例
Posted Nancy26
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于C基于客户端的通信实例的主要内容,如果未能解决你的问题,请参考以下文章