Get the App
SLTechnology News&Howtos  ›  Servers  › 

C++socket Network programming (Cross-platform) practical HTTP Server (3)

Shulou Source: shulou.com Published: 2022-06-03 00:19:24 09月22日 Update

Encapsulate the TCP class

Encapsulate the tcp class, and the steps can be simplified

Put the code class name directly: XTCP

Xtcp.h

# ifndef _ XTCP_H_#define _ XTCP_H_#include # include class XTCP {public:XTCP (); virtual ~ XTCP (); public:int CreateSocket (); / create socket estoppel socketbool Bind (unsigned short port); / / bind port XTCP Accept (); / / return an object void Close (); / / turn off active int Recv (char * buf, int bufsize); / / receive int Send (const char * buf, int sendsize); / / send int m_sock = 0scape unsigned short m_port = 0 Std::string ip;}; # endif / / _ XTCP_H_

Xtcp.cpp

# include "XTCP.h" # ifdef WIN32#include # define socklen_t int#else#include # define closesocket close#include # endifXTCP::XTCP () {# ifdef WIN32static bool first = true; / / guarantee to enter if (first) {first = false;WSADATA ws;WSAStartup (MAKEWORD (2,2), & ws);} # endif} XTCP::~XTCP () {} int XTCP::CreateSocket () {m_sock = socket (AF_INET, SOCK_STREAM, 0) If (m_sock = =-1) {printf ("create socket failed!\ n");} return masked socks;} bool XTCP::Bind (unsigned short port) {sockaddr_in sa;sa.sin_family = AF_INET;sa.sin_port = htons (port); sa.sin_addr.s_addr = htonl (0); if (bind (m_sock, (sockaddr*) & sa, sizeof (sa)) {printf ("bind port err\ n"); / / binding succeeded return false } / / listen on listen (m_sock, 10); / / failed to bind return true;} void XTCP::Close () {if (m_sock)

Tags: Thread object that is encapsulation success function code size byte user port resource length face guarantee server network service initiative previous generation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker NVidia OPPO Reno Shulou Information Shulou Technology