首页 > 代码库 > C基于客户端的通信实例
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 = http://www.mamicode.com/"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基于客户端的通信实例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。