C++自定义封装socket操作业务类完整实例

本文实例讲述了C++自定义封装socket操作业务类。分享给大家供大家参考,具体如下:

Linux下C++封装socket操作的工具类(自己实现)

socketconnector.h

#ifndef SOCKETCONNECTOR_H
#define SOCKETCONNECTOR_H
#include "global.h"
using namespace std;
class SocketConnector
{
public:
  typedef enum {
    ENormal,
    EOther,
  } SocketState;
public:
  static SocketConnector * getInstance();
  inline SocketState state(){ return m_state; }
  inline void setState(SocketState _state){  m_state = _state;  }
  inline bool isConnected() { return m_isConnected;  }
  inline void setConnected(bool state) { m_isConnected = state; }
  void start();
  inline void setServerIP(string ip){  m_server_ip = ip;}
  inline void setServerPort(int port){ m_server_port = port; }
  int connect_sockfd();
  int onSendMessage(string & message);
private:
  SocketConnector();
  void onConnectToServer(string & ip,int port);
  static void * onReportMessage(void * p);
  static void * onReadMessage(void * p);
  static void * onWriteMessage(void * p);
private:
  SocketState m_state;
  bool m_isConnected;
  int m_sockFd;
  string m_server_ip;
  int m_server_port;
  pthread_t m_report_tid;
  pthread_t m_read_tid;
  pthread_t m_write_tid;
};
#endif // SOCKETCONNECTOR_H

socketconnector.cpp

#include "global.h"
#include "socketconnector.h"
#include "cmessagecenter.h"
#include "cmip_requestparser.h"
#include "csettings.h"
#include "datadef.h"
#include "cstringutils.h"
using namespace std;
static SocketConnector * g_instance = NULL;
/**************************************************************************************************
*  Single Instance.
***************************************************************************************************/
SocketConnector * SocketConnector::getInstance()
{
  if (g_instance == NULL)
  {
    g_instance = new SocketConnector();
  }
  return g_instance;
}
/**************************************************************************************************
*  Consturoctor
***************************************************************************************************/
SocketConnector::SocketConnector()
{
  m_isConnected = false;
  m_state = ENormal;
}
/**************************************************************************************************
*  Connect to Server By Blocking Method.
***************************************************************************************************/
void SocketConnector::onConnectToServer(string & ip,int port){
  cout << __FUNCTION__ << "connecting::[" << ip << " , " << port << "]" << endl;
  struct timeval send_timeout;
  send_timeout.tv_sec = 5;
  send_timeout.tv_usec = 0;
  int keepalive = 1;
  int keepidle = 10;
  int keepinterval = 5;
  int keepcount = 3;
  int value = 0;
  socklen_t len = sizeof(int);
  static struct sockaddr_in server_addr;
  memset(&server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(port);
  server_addr.sin_addr.s_addr = inet_addr(ip.c_str());
  do
  {
    m_sockFd = socket(AF_INET, SOCK_STREAM, 0);
    if ( -1 == m_sockFd )
    {
      sleep(1);
      continue;
    }
  }while(-1 == m_sockFd);
  if(setsockopt(m_sockFd, SOL_SOCKET, SO_SNDTIMEO, &send_timeout, sizeof(send_timeout)) == -1)
  {
    printf("setsockopt SO_SNDTIMEO fail\n");
  }
  if(setsockopt(m_sockFd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive , sizeof(keepalive )) == -1)
  {
    printf("setsockopt SO_KEEPALIVE fail\n");
  }
  if(setsockopt(m_sockFd, SOL_TCP, TCP_KEEPIDLE, (void*)&keepidle , sizeof(keepidle )) == -1)
  {
    printf("setsockopt TCP_KEEPIDLE fail\n");
  }
  if(setsockopt(m_sockFd, SOL_TCP, TCP_KEEPINTVL, (void *)&keepinterval , sizeof(keepinterval )) == -1)
  {
    printf("setsockopt TCP_KEEPINTVL fail\n");
  }
  if(setsockopt(m_sockFd, SOL_TCP, TCP_KEEPCNT, (void *)&keepcount , sizeof(keepcount )) == -1)
  {
    printf("setsockopt TCP_KEEPCNT fail\n");
  }
  getsockopt(m_sockFd, SOL_TCP, TCP_KEEPINTVL, (void *)&value, &len);
  cout << __FUNCTION__ << "sockFd KeepIntval::[" << value << endl;
  while (!m_isConnected)
  {
    if(connect(m_sockFd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == 0)
    {
      m_isConnected = true;
      break;
    }
    else
    {
      if ( ECONNREFUSED == errno)
      {
        m_isConnected = false;
        sleep(1);
        printf("Reconnect To Server:%s Port:%d\n", m_server_ip.c_str(), m_server_port);
      }
      else
      {
        m_isConnected = false;
        perror("connected() error()");
        exit(-1);
      }
    }
  }
}
/**************************************************************************************************
*  Create Report Thread;
*  Create Read Thread;
*  Create Write Thread;
*  MainThread wait the subThreads exits;
***************************************************************************************************/
void SocketConnector::start()
{
  m_sockFd = connect_sockfd();
  cout << __FUNCTION__ << "Will Create Report|Read|Write Thread." << endl;
  pthread_create(&m_report_tid,NULL, onReportMessage, this);  /* report to cmdmodule*/
  pthread_create(&m_read_tid, NULL, onReadMessage, this);  /* read from cmdmodule*/
  pthread_create(&m_write_tid, NULL, onWriteMessage, this);  /* reply to cmdmodule*/
  pthread_join(m_read_tid,NULL);
  pthread_join(m_write_tid,NULL);
  pthread_join(m_report_tid,NULL);
}
/**************************************************************************************************
*  Used to Get connected socket fd.
*  if connected, return directly.
*  if not connected,try to create connect fd.
***************************************************************************************************/
int SocketConnector::connect_sockfd()
{
  if ( m_isConnected == true)
  {
    cout << __FUNCTION__ << "::Socket is Already Connected." << endl;
    return m_sockFd;
  }
  cout << __FUNCTION__ << "::Will Try to Connect to Server." << endl;
  onConnectToServer(m_server_ip, m_server_port);
  return m_sockFd;
}
/**************************************************************************************************
*  Report Status to CmdModule Thread.
*  every 2s ,report one message to cmdwifi.
***************************************************************************************************/
void * SocketConnector::onReportMessage(void * p)
{
  SocketConnector * connector = (SocketConnector *)(p);
  if ( NULL == p)
  {
    cout << __FUNCTION__ << "onSelectSocket() Error: param [connector] is NULL" << endl;
    return NULL;
  }
  string content;
  int devType = atoi(CSettings::getInstance()->getKuType().c_str());
  int report_interval = atoi(CSettings::getInstance()->getKuReportinterval().c_str());
  string position = CSettings::getInstance()->getKuPosition();
  string local_ip = CSettings::getInstance()->getKuAgentip();
  cout << endl;
  cout << "###################################" << endl;
  cout << "Local-IP::" << local_ip << endl;
  cout << "Ku-CMA-Pos::" << position << endl;
  cout << "Ku-CMA-Type::" << devType << endl;
  cout << "###################################" << endl;
  cout << endl;
  while(true)
  {
    int state = connector->state();
    content = "<status>" + CStringUtils::toString(state) + "</status>";
    content += "<type>" + CStringUtils::toString(devType) + "</type>";
    content += "<site>" + position + "</site>";
    content += "<ip>" + local_ip + "</ip>";
    Response resp(STATUS_REPORT_CMD,0,string(content));
    CMessageCenter::getInstance()->addReply(resp);
    sleep(report_interval);
  }
}
/**************************************************************************************************
*  Read Message from Connection.
*  Then Send Message to MessageCenter Queue.
***************************************************************************************************/
void * SocketConnector::onReadMessage(void * p)
{
  SocketConnector * connector = (SocketConnector *)(p);
  if ( NULL == p)
  {
    cout << __FUNCTION__ << "onSelectSocket() Error: param [connector] is NULL" << endl;
    return NULL;
  }
  int sockFd = connector->connect_sockfd();
  fd_set fds;
  struct timeval timeout={0,0};
  const int BUFFER_LEN = 4*1024;
  static char buffer[BUFFER_LEN]={0};
  while(true)
  {
    FD_ZERO(&fds);
    FD_SET(sockFd,&fds);
    int ret = select(sockFd + 1,&fds,NULL,NULL,&timeout);
    switch (ret) {
      case -1:/*Error process*/
      {
        perror("select()");
        if ( EBADF == errno)
        {
          close(sockFd);
          connector->setConnected(false);
          sleep(1);
          sockFd = connector->connect_sockfd();
          continue;
        }
        if ( EINTR == errno || ENOMEM == errno)
        {
          sleep(1);
          continue;
        }
      }break;
      case 0:
      {
        //cout << "select() timeout! " << endl;
      }break;
      default:
      {
        if(FD_ISSET(sockFd,&fds))
        {
          memset(buffer, 0, BUFFER_LEN);
          int nRead = read(sockFd, buffer, BUFFER_LEN);
          cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" << endl;
          cout << "From Server Recevied Data::" << string(buffer) << endl;
          cout << "From Server Recevied Length::" << nRead << endl;
          cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" << endl;
          CRequestParser parser;
          Request req;
          int ret = parser.parseToMessage(buffer,&req);
          if (0 != ret)
          {
            cout << __FUNCTION__ << "Request Format is invalid" << endl;
            continue;
          }
          req.print();
          CMessageCenter::getInstance()->addRequest(req);
        }
      }break;
    }
  }
}
/**************************************************************************************************
*  Write Message to Connection.
*  Then Send Message to MessageCenter Queue.
***************************************************************************************************/
void * SocketConnector::onWriteMessage(void * p)
{
  SocketConnector * connector = (SocketConnector *)(p);
  if ( NULL == p)
  {
    cout << __FUNCTION__ << "onSelectSocket() Error: param [connector] is NULL" << endl;
    return NULL;
  }
  while (true)
  {
      Response msg;
      CMessageCenter::getInstance()->getReplyMsg(msg);
      string data = CMessageEncoder(msg).encode();
      connector->onSendMessage(data);
  }
}
/**************************************************************************************************
*  Send Message By Socket.
***************************************************************************************************/
int SocketConnector::onSendMessage(string & strSend)
{
  if (atoi(CSettings::getInstance()->getDebugMode().c_str()) == 1)
  {
    cout << __FUNCTION__ << "Send To Cmdwifi Data::" << endl;
    cout << strSend << endl;
  }
  int sock = m_sockFd;
  char *pData = &strSend[0];
  int nLen = static_cast<int>(strSend.size());
  int nTotal = nLen;
  int i = 0;
  while(1)
  {
    int nTmp = send(sock, &pData[i], nTotal, 0);
    if (nTmp <= 0)
    {
      close(sock);
      return -1;
    }
    nTotal -= nTmp;
    i += nTmp;
    if (nTotal <= 0)
    {
      break;
    }
  }
  return 0;
}

希望本文所述对大家C++程序设计有所帮助。

(0)

相关推荐

  • C++类继承之子类调用父类的构造函数的实例详解

    C++类继承之子类调用父类的构造函数的实例详解 父类HttpUtil: #pragma once #include <windows.h> #include <string> using namespace std; class HttpUtil { private: LPVOID hInternet; LPVOID hConnect; LPVOID hRequest; protected: wchar_t * mHostName; short mPort; string send

  • C++中的聚合类定义与用法分析

    本文实例讲述了C++中的聚合类.分享给大家供大家参考,具体如下: 聚合类是一种没有用户定义的构造函数,没有私有(private)和保护(protected)非静态数据成员,没有基类,没有虚函数.这样的类可以由封闭的大括号用逗号分隔开初始化列表.下列的代码在 C 和 C++ 具有相同的语法: struct C { int a; double b; }; struct D { int a; double b; C c; }; // initialize an object of type C wit

  • C++ 类的继承与派生实例详解

     C++ 类的继承与派生实例详解 继承性是面向对象程序设计最重要的特性之一,使软件有了可重用性,C++提供的类的继承机制. 继承与派生的概念 一个新类从已有的类那里获得已有的特性,这种现象称为类的继承.同样也可以说成已有的类派生出来了新的类.类A继承自类B也就是类B派生了类A.所以继承和派生的关系就像小学时把字句和被字句的造句一样.有了继承与派生后,就有了父类/基类与子类/派生类,C++中将类B称为父类/基类,将类A称为子类/派生类. 派生类的声明: #include <iostream> u

  • C++中继承与多态的基础虚函数类详解

    前言 本文主要给大家介绍了关于C++中继承与多态的基础虚函数类的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 虚函数类 继承中我们经常提到虚拟继承,现在我们来探究这种的虚函数,虚函数类的成员函数前面加virtual关键字,则这个成员函数称为虚函数,不要小看这个虚函数,他可以解决继承中许多棘手的问题,而对于多态那他更重要了,没有它就没有多态,所以这个知识点非常重要,以及后面介绍的虚函数表都极其重要,一定要认真的理解~ 现在开始概念虚函数就又引出一个概念,那就是重写(覆

  • 详解C++的String类的字符串分割实现

    详解C++的String类的字符串分割实现 功能需求,输入一个字符串"1-2-3"切割出"1"."2"."3".在Java下直接用String的split函数就可以了.c++下String没有直接提供这个函数,需要自己写. 网上给出的解决方案是这里的三种方法.但我是通过JNI访问的,在里面用这些vector可能不中,自己封装了个,仅供参考: String recogScop = "01-02-03"; co

  • C++ 中类的拷贝、赋值、销毁的实例详解

    C++ 中类的拷贝.赋值.销毁的实例详解 本篇文章我们一共讲解一下几个知识点: 类的拷贝构造函数. 类的拷贝赋值运算符. 类的析构. 好了one by one 如果我们没有定义类的拷贝构造函数的话,那么编译器会为我们合成默认拷贝构造函数----合成拷贝构造函数. 和成拷贝构造函数的操作是将其参数的各个成员拷贝到正在创建的对象中去,每个成员的类型决定了他是如何被拷贝的:对类类型的成员,会使用其拷贝构造函数,内置类型的成员则是直接拷贝,虽然我们不能直接拷贝一个数组,但是合成拷贝构造函数会逐个的拷贝一

  • C++自定义封装socket操作业务类完整实例

    本文实例讲述了C++自定义封装socket操作业务类.分享给大家供大家参考,具体如下: Linux下C++封装socket操作的工具类(自己实现) socketconnector.h #ifndef SOCKETCONNECTOR_H #define SOCKETCONNECTOR_H #include "global.h" using namespace std; class SocketConnector { public: typedef enum { ENormal, EOth

  • php封装的验证码工具类完整实例

    本文实例讲述了php封装的验证码工具类.分享给大家供大家参考,具体如下: <?php //验证码工具类 class Captcha{ //属性 private $width; private $height; private $fontsize; private $pixes; private $lines; private $str_len; /* * 构造方法 * @param1 array $arr = array(),初始化属性的关联数组 */ public function __con

  • php封装的page分页类完整实例

    本文实例讲述了php封装的page分页类.分享给大家供大家参考,具体如下: 类文件: <?php //分页工具类 class Page{ /* * 获取分页字符串 * @param1 string $uri,分页要请求的脚本url * @param3 int $counts,总记录数 * @param4 int $length,每页显示的记录数 * @param5 int $page = 1,当前页码 * @return string,带有a标签的,可以点击发起请求的字符串 */ public

  • PHP数据库操作Helper类完整实例

    本文实例讲述了PHP数据库操作Helper类.分享给大家供大家参考,具体如下: php操作数据库分为几个步骤(这里以MYSQL为例): 1. 建立连接 $connection=mysql_connect($db_host,$db_username,$db_password); 2. 选择数据库 $db_select=mysql_select_db($db_database); 3. 执行CRUD操作 mysql_query("set names 'utf8'");//编码 $resul

  • C#操作ftp类完整实例

    本文实例讲述了C#操作ftp类.分享给大家供大家参考.具体如下: using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Globalization; namespace FtpTest1 { public class FtpWeb { string ftpServerIP; string ftpRemotePath; st

  • php封装的page分页类完整实例代码

    效果图 1.测试实例test.php <?php header("Content-Type: text/html; charset=utf-8"); date_default_timezone_set("Asia/Shanghai"); //时区 require_once('page.class.php'); $showrow = 5; $curpage = empty($_GET['page']) ? 1 : $_GET['page']; $url = &q

  • C#自定义的字符串操作增强类实例

    本文实例讲述了C#自定义的字符串操作增强类.分享给大家供大家参考.具体如下: 这个C#类在C#自由的字符串操作类的基础上进行的大幅度增强,把我们平时可能用到的字符串操作都做进去了,字符串的处理我想大部分编程都不可避免,有了这个类,可以节省你很多时间,同时可以根据自己的需要对这个C#字符串类进行扩展. using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpress

  • java自定义封装StringUtils常用工具类

    自定义封装StringUtils常用工具类,供大家参考,具体内容如下 package com.demo.utils; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 字符串操作工具类 * @author dongyangyang * @Date 2016/12/28 23:12 * @Version 1.0 * */ public class StringUtils { /** * 首字

  • Path类 操作文件类的实例

    // Path类 IO命名空间 静态类 不能创建对象类名. string str =@"E:\C#程序设计基础入门教程\(第十一天)\122\22\nee.txt"; ////int index=str.LastIndexOf ("\\")//最后一出现的位置 ////str =str.Substring (index +1);//拿到最后一个文件 ////Console.WriteLine(str); Console.WriteLine(Path.GetFileN

  • PHP封装的数据库模型Model类完整示例【基于PDO】

    本文实例讲述了PHP封装的数据库模型Model类.分享给大家供大家参考,具体如下: <?php //引入配置文件 include "../Config/config.php"; class Model extends PDO { protected $tableName = "";//存储表名 protected $sql = "";//存储最后执行的SQL语句 protected $limit = "";//存储lim

随机推荐