Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

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)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report