基于Linux的socket编程模板(3)

来源:未知 责任编辑:责任编辑 发表时间:2014-01-20 07:53 点击:

/// @E-mail  lujun.hust@gmail.com 
/// @date    2011/08/21 
// 
// 
//  修订说明: 
////////////////////////////////////////////////////////////////////////// 
 
#include <stdio.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <unistd.h> 
#include <errno.h> 
#include <string.h> 
#include "client.h" 
 
// socket handle 
int g_hSocket; 
 
int connect_server( char *destIp, int destPort ) 

    int result; 
    struct sockaddr_in address; 
 
    // create a socket 
    g_hSocket = socket(AF_INET,SOCK_STREAM,0); 
 
    // set server addr 
    address.sin_family = AF_INET; 
 
    // use server ip and listen port to connect 
    address.sin_addr.s_addr = inet_addr( destIp ); 
    address.sin_port        = htons(destPort); 
     
    // connect tcp server 
    result = connect(g_hSocket,(struct sockaddr *)&address,sizeof(address) ); 
    if( result == -1 ) 
    { 
        printf("[tcp client] can't connect server !\n"); 
          return -1; 
    } 
     
    return 0; 

 
int close_connect() 

    printf("close connect with server !\n "); 
 
    close(g_hSocket); 
 
    return 0; 

 
int send_cmd( ServerPack sPack ) 

    int recvBytes = 0; 
    int sendBytes = 0; 
    ReturnPack rPack; 
 
    // add cmd header 
    memcpy(sPack.cmdHeader,TCP_CMD_HEADER_STR,TCP_CMD_HEADER_LEN); 
 
    // send cmd 
    while(1) 
    { 
        sendBytes = send(g_hSocket,(uint8_t *)&sPack,SERVER_PACK_LEN,0); 
         
        if( sendBytes == SERVER_PACK_LEN ) 
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • /etc/fstab 详解
  • nginx主主集群
  •  LVS-NAT和LVS-DR模式的实现详解
  •  RHCE考试之磁盘配额
  • 学习笔记:ACL详解
  • suse linux双网卡双网关配置
  •  LVM逻辑卷管理器
  •  Nginx主主负载均衡架构
  • ubuntu学习Mysql

快速直达

操作系统导航

LinuxWindows虚拟机
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1