freecplus network communication frame -tcp

A source code description

freecplus is a C / C ++ open source framework under a Linux system, go to the C language source code Technology Network (www.freecplus.net) download.

This article describes the TCP / IP protocol-based network communication functions and freecplus frame.

Declaration file functions and classes are freecplus / _freecplus.h.

Definition file functions and classes are freecplus / _freecplus.cpp.

Sample program located freecplus / demo directory.

Compiled rules file is freecplus / demo / makefile.

Second, an overview

freecplus framework socket communication package as follows:

CTcpClient categories: communication socket client class.

CTcpServer class: class server socket communication.

TcpRead functions: receiving data sent from the socket to the end.

TcpWrite functions: sends data to the end of the socket.

Readn function: read data from the socket has been prepared.

Writen function: to write the data has been prepared in the socket.

Before reading this article, you must be familiar with TCP / IP protocol and socket communication, this is an introductory class is the usage and functions freecplus framework of network communication, will not cover the basics of network communications.

Third, the communication message format

freecplus socket communication message frame format is as follows:

Message length + message content

Packet length is an integer of 4 bytes indicating the content of the packet length, rather than the entire length of the TCP packet, the entire length of the TCP packet is the length of the message contents +4 .

Packet length is an integer of 4 bytes, i.e. int, is written in socket, not the binary stream ascii code embodiment.

Using CTcpClient class, CTcpServer class, TcpRead TcpWrite functions and communication functions socket, TCP packets can be avoided stick package problems.

Four, socket communication client

The client package socket communication CTcpClient class.

Class declaration:

// socket通信的客户端类
class CTcpClient
{
public:
  int  m_sockfd;    // 客户端的socket.
  char m_ip[21];    // 服务端的ip地址。
  int  m_port;      // 与服务端通信的端口。
  bool m_state;     // 与服务端的socket连接状态。
  bool m_btimeout;  // 调用Read和Write方法时,失败的原因是否是超时:true-未超时,false-已超时。
  int  m_buflen;    // 调用Read方法后,接收到的报文的大小,单位:字节。

  CTcpClient();  // 构造函数。

  // 向服务端发起连接请求。
  // ip:服务端的ip地址。
  // port:服务端监听的端口。
  // 返回值:true-成功;false-失败。
  bool ConnectToServer(const char *ip,const int port);

  // 接收服务端发送过来的数据。
  // buffer:接收数据缓冲区的地址,数据的长度存放在m_buflen成员变量中。
  // itimeout:等待数据的超时时间,单位:秒,缺省值是0-无限等待。
  // 返回值:true-成功;false-失败,失败有两种情况:1)等待超时,成员变量m_btimeout的值被设置为true;2)socket连接已不可用。
  bool Read(char *buffer,const int itimeout=0);

  // 向服务端发送数据。
  // buffer:待发送数据缓冲区的地址。
  // ibuflen:待发送数据的大小,单位:字节,缺省值为0,如果发送的是ascii字符串,ibuflen取0,如果是二进制流数据,ibuflen为二进制数据块的大小。
  // 返回值:true-成功;false-失败,如果失败,表示socket连接已不可用。
  bool Write(const char *buffer,const int ibuflen=0);

  // 断开与服务端的连接
  void Close();

  ~CTcpClient();  // 析构函数自动关闭socket,释放资源。
};

Fifth, the server socket communication

Communication server socket encapsulated in CTcpServer class.

Class declaration:

// socket通信的服务端类
class CTcpServer
{
private:
  int m_socklen;                    // 结构体struct sockaddr_in的大小。
  struct sockaddr_in m_clientaddr;  // 客户端的地址信息。
  struct sockaddr_in m_servaddr;    // 服务端的地址信息。
public:
  int  m_listenfd;   // 服务端用于监听的socket。
  int  m_connfd;     // 客户端连接上来的socket。
  bool m_btimeout;   // 调用Read和Write方法时,失败的原因是否是超时:true-未超时,false-已超时。
  int  m_buflen;     // 调用Read方法后,接收到的报文的大小,单位:字节。

  CTcpServer();  // 构造函数。

  // 服务端初始化。
  // port:指定服务端用于监听的端口。
  // 返回值:true-成功;false-失败,一般情况下,只要port设置正确,没有被占用,初始化都会成功。
  bool InitServer(const unsigned int port); 

  // 阻塞等待客户端的连接请求。
  // 返回值:true-有新的客户端已连接上来,false-失败,Accept被中断,如果Accept失败,可以重新Accept。
  bool Accept();

  // 获取客户端的ip地址。
  // 返回值:客户端的ip地址,如"192.168.1.100"。
  char *GetIP();

  // 接收客户端发送过来的数据。
  // buffer:接收数据缓冲区的地址,数据的长度存放在m_buflen成员变量中。
  // itimeout:等待数据的超时时间,单位:秒,缺省值是0-无限等待。
  // 返回值:true-成功;false-失败,失败有两种情况:1)等待超时,成员变量m_btimeout的值被设置为true;2)socket连接已不可用。
  bool Read(char *buffer,const int itimeout);

  // 向客户端发送数据。
  // buffer:待发送数据缓冲区的地址。
  // ibuflen:待发送数据的大小,单位:字节,缺省值为0,如果发送的是ascii字符串,ibuflen取0,如果是二进制流数据,ibuflen为二进制数据块的大小。
  // 返回值:true-成功;false-失败,如果失败,表示socket连接已不可用。
  bool Write(const char *buffer,const int ibuflen=0);

  // 关闭监听的socket,即m_listenfd,常用于多进程服务程序的子进程代码中。
  void CloseListen();

  // 关闭客户端的socket,即m_connfd,常用于多进程服务程序的父进程代码中。
  void CloseClient();

  ~CTcpServer();  // 析构函数自动关闭socket,释放资源。
};

Sixth, the sample program

1, the client

Example (demo47.cpp)

/*
 *  程序名:demo47.cpp,此程序演示采用freecplus框架的CTcpClient类实现socket通信的客户端。
 *  作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include "../_freecplus.h"

int main(int argc,char *argv[])
{
  CTcpClient TcpClient;   // 创建客户端的对象。
  
  if (TcpClient.ConnectToServer("172.16.0.15",5858)==false) // 向服务端发起连接请求。
  {
    printf("TcpClient.ConnectToServer(\"172.16.0.15\",5858) failed.\n"); return -1;
  }

  char strbuffer[1024];    // 存放数据的缓冲区。

  for (int ii=0;ii<5;ii++)   // 利用循环,与服务端进行5次交互。
  {
    memset(strbuffer,0,sizeof(strbuffer));
    snprintf(strbuffer,50,"这是第%d个超级女生,编号%03d。",ii+1,ii+1);
    printf("发送:%s\n",strbuffer);
    if (TcpClient.Write(strbuffer)==false) break;    // 向服务端发送请求报文。

    memset(strbuffer,0,sizeof(strbuffer));
    if (TcpClient.Read(strbuffer,20)==false) break;  // 接收服务端的回应报文。
    printf("接收:%s\n",strbuffer);

    sleep(1);
  }

  // 程序直接退出,析构函数会释放资源。
}

2, the server

Example (demo48.cpp)

/*
 *  程序名:demo48.cpp,此程序演示采用freecplus框架的CTcpServer类实现socket通信的服务端。
 *  作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include "../_freecplus.h"

int main(int argc,char *argv[])
{
  CTcpServer TcpServer;   // 创建服务端对象。
  
  if (TcpServer.InitServer(5858)==false) // 初始化TcpServer的通信端口。
  {
    printf("TcpServer.InitServer(5858) failed.\n"); return -1;
  }
  
  if (TcpServer.Accept()==false)   // 等待客户端连接。
  {
    printf("TcpServer.Accept() failed.\n"); return -1;
  }

  printf("客户端(%s)已连接。\n",TcpServer.GetIP());

  char strbuffer[1024];  // 存放数据的缓冲区。

  while (true)
  {
    memset(strbuffer,0,sizeof(strbuffer));
    if (TcpServer.Read(strbuffer,300)==false) break; // 接收客户端发过来的请求报文。
    printf("接收:%s\n",strbuffer);

    strcat(strbuffer,"ok");      // 在客户端的报文后加上"ok"。
    printf("发送:%s\n",strbuffer);
    if (TcpServer.Write(strbuffer)==false) break;     // 向客户端回应报文。
  }

  printf("客户端已断开。\n");    // 程序直接退出,析构函数会释放资源。
}

3, ready to run the program before the end of

I hope you have learned the basics of computer networks, before you run the sample program, make sure that your firewall Linux operating system has been opened.

In demo47.cpp and demo48.cpp program, ip address and communications port server is hard-coded in the program, modify them according to your situation, and then recompile.

4, run the program

First start demo48, then start demo47.

Demo47 operating results are as follows:

Here Insert Picture Description

Demo48 operating results are as follows:

Here Insert Picture Description

Seven function socket communication

And using CTcpClient CTcpServer socket class implements a communication function is very convenient, but in the actual development, certain scenarios can not rely on two classes, for example, a multi-scene process lines and asynchronous communications, must also combine several functions which will be described use together.

1, TcpRead function

Data sent from the receiving end of the socket.

Function declaration:

bool TcpRead(const int sockfd,char *buffer,int *ibuflen,const int itimeout=0);

Parameter Description:

sockfd: Available socket connection.

buffer: receiving data buffer address.

ibuflen: The number of bytes successfully received data.

itimeout: reception waiting timeout, unit: second default value is from 0 to wait indefinitely.

Return Value: true-success; false-failure, failure, there are two cases: 1) Wait Timeout; 2) socket connection is unavailable.

Call TcpRead function in the Read method CTcpClient and CTcpServer class.

2, TcpWrite function

Send data to the end of the socket.

Function declaration:

bool TcpWrite(const int sockfd,const char *buffer,const int ibuflen=0);

Parameter Description:

sockfd: Available socket connection.

buffer: buffer address data to be transmitted.

ibuflen: the number of bytes of data to be transmitted, if the transmission is an ascii string, ibuflen be 0, if the binary data stream, ibuflen is the size of the binary data block.

Return Value: true- successful; false-failure, if it fails, showing the socket connection has been unavailable.

TcpRead function calls the Write method CTcpClient and CTcpServer class.

3, Readn function

Read data from the socket has been prepared.

Function declaration:

bool Readn(const int sockfd,char *buffer,const size_t n);

sockfd: socket connection has been prepared.

buffer: receiving data buffer address.

n: The number of bytes of received data.

Returns true successfully received the data of n bytes, socket connection is not available returns false: the return value.

note:

1) sockfd socket connection is already prepared, what we are already prepared socket? In this socket, or immediately we have an n-byte data will arrive.

Returns true after 2) successfully received n bytes of data, how if not n bytes of data to do? No, 1) has been explained, there will be n bytes of data will arrive.

3) If the data is larger than n bytes how to do? Readn n bytes read only data, other data belonging to other packets.

4) of the socket end Writen method is the use of the data writing.

In TcpRead function, call the Readn function.

4, Writen function

It has been prepared to write data to the socket.

Function declaration:

bool Writen(const int sockfd,const char *buffer,const size_t n);

sockfd: socket connection has been prepared.

buffer: buffer address data to be transmitted.

n: Number of bytes to transmit data.

Return Value: returns true after a successful completion of transmitting n-byte data, socket connection is unavailable returns false.

In TcpWrite function, called Writen function.

Eight, copyright notice

C Language Technology Network original article, reproduced please indicate the source link to the article, the author and original.
Source: C Language Technology Network (www.freecplus.net)
Author: Ethics code Agriculture

If the article typos, or content errors, or other suggestions and comments, please correct me message, thank you very much! ! !

Published 159 original articles · won praise 458 · views 120 000 +

Guess you like

Origin blog.csdn.net/wucz122140729/article/details/105187597