Using a class to achieve network communication functions:

Source: Internet
Author: User
TCP/IP communication classBackground or reason: often use network communication, in order to facilitate, write a class, so that it can work like a stream.

Environment: Windows system, executable C + + program, network connection Normal

Specific function: Complete TCP/IP communication. The TCP server, TCP client, UDP is optional, in a similar flow mode and the use of ">>", "<<" to receive and send, and the amount of transport optional.

Use examples:

#include "nstream.h"
int main ()
{
nstream TCPs (8000);//Select TCP Server port: 8000
char c[6] = "Hello";
while (1)
{
tcps<<c;//sends 6 characters
tcps>>c;//receives 6 characters} return
0;
}

Header file "nstream.h":

#include <Windows.h> #pragma comment (lib, "Ws2_32.lib") class Nstream {public:nstream (const int tcplocport4ser); n
Stream (const char* TCPREMIPADD4CLI, const int TCPSERPOR4CLI);
Nstream (const int UDPLOCPORT,CONST char* udpremipadd, const int udpremport);
~nstream ();
int Getn ();
Private:bool Init ();

BOOL Createsocket (int type, int protocol);
BOOL Bindsock ();
BOOL Listen (const int n);

BOOL Accept ();

BOOL Connect (); Where T cannot make pointer types (array header pointers can) Template<typename t> friend nstream& operator << (nstream& os, const T &AMP;STR UCT) {sockaddr_in sockadd = os. Struadd; The IF (OS) must be assigned. Tratype)//udp {os.num = sendto (OS).
Sock, (const char*) &struct,sizeof (Struct), 0, (const SOCKADDR *) &sockadd, sizeof (SOCKADDR)); else if (os.num = Send (OS. Sock, (const char*) &struct,sizeof (Struct), 0) = = socket_error) {cout<< "Send Info ERROR::" <<
GetLastError () <<endl;
Throw ("");}
return OS; }//where t cannot make pointer type (array header pointer can) Template<typename t> friend nstream& OperAtor >> (nstream& in, const T &struct) {int len = sizeof (SOCKADDR); Sockaddr_in sockadd;//= in. Struadd; You must not assign a value if (in. Tratype)//udp {in.num =recvfrom (in.
Sock, (char*) &struct, sizeof (Struct), 0, (sockaddr*) &sockadd,&len); else if (In.num = (in. Sock, (char*) &struct, sizeof (Struct), 0) = = 0 | |
In.num = = socket_error) {cout<< "Recv Info ERROR::" <<getlasterror () <<endl;
Throw ("");}
return in; } Private:wsadata Ws; Version number bool Tratype; False->tcp, true->udp SOCKET sock;
Work SOCKET serversock;//only TCPs use struct sockaddr_in struadd; int num;//the number of characters or status of the transmission};

source file "Nstream.cpp":

<pre name= "code" class= "CPP" > #include "nstream.h" #include <iostream> using namespace std;
Tcp_server nstream::nstream (const int tcplocport4ser): Tratype (false), num (0) {Init (); STRUADD.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");//32-bit IP address htonl (inaddr_any) = = inet_addr ("127.0.0.1") struadd.sin_

Port = htons (Tcplocport4ser);//16-bit port number Createsocket (Sock_stream, ipproto_tcp);

Bindsock ();
Listen (10);
Accept ();
}//tcp_client Nstream::nstream (const char* TCPREMIPADD4CLI, const int tcpserpor4cli): Tratype (false), num (0) {Init ();
STRUADD.SIN_ADDR.S_ADDR = inet_addr (TCPREMIPADD4CLI);

Struadd.sin_port = htons (TCPSERPOR4CLI);

Createsocket (Sock_stream, ipproto_tcp);
Connect (); }//udp_server && CLIENT nstream::nstream (const int UDPLOCPORT,CONST char* udpremipadd, const int udpremport): Tra
Type (True), num (0) {Init ();
STRUADD.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");

Struadd.sin_port = htons (Udplocport);

Createsocket (sock_dgram, 0);

Bindsock (); Struadd.sin_addr.S_ADDR = inet_addr (Udpremipadd);
Struadd.sin_port = htons (Udpremport); }//destructor Nstream::~nstream () {}//Get transport return value int nstream::getn () {<span style= "white-space:pre" > </span>return nu
M }//Initialize bool Nstream::init () {if (WSAStartup (Makeword (2,2), &ws)) {cout<< "Init Windows Socket Failed::" <&lt ;
GetLastError () <<endl;
Throw (""); 
return false; } if (Lobyte (ws.wversion)!=2 | |
Hibyte (ws.whighversion)!=2) {wsacleanup (); cout<< "Init Windows Socket Failed" <<endl; throw ("");
return false;
struadd.sin_family = af_inet;//protocol family, must be Af_inet memset (Struadd.sin_zero, 0x00, 8);
return true;  ///Create socket BOOL Nstream::createsocket (int type, int protocol) {sock = Serversock = socket (af_inet, type, protocol); if (
Sock = = Invalid_socket) {cout<< "Create SOCKET Failed::" <<getlasterror () <<endl;
Throw ("");
return false;
return true; //tcps bind bool Nstream::bindsock () {if (bind Serversock, (struct sockaddr*) &struadd, sizeof (SOCKADDR))!= 0) {cout<< "Bind Socket Failed::" <<getlasterror () <<endl;
Throw (""); 
return false;
return true; //TCPS monitor bool Nstream::listen (const int n) {if (Listen (Serversock, N)!= 0) {cout<< "Listen Socket Failed::" 
; <getlasterror () <<endl;
Throw ("");
return false;
return false;
//tcps Accept connection request bool Nstream::accept () {int addrlen = sizeof (STRUADD); Sock = Accept (Serversock, (struct sockaddr*) &struadd, &addrlen);//-------if (sock = invalid_socket) {cout<
< "Accept Failed::" <<getlasterror () <<endl;
Throw (""); 
return false;
return true;  //TCPC Request connection bool Nstream::connect () {if (Connect (sock, (struct sockaddr*) &struadd, sizeof (struadd)) = = Socket_error
{cout<< "Connect Error::" <<getlasterror () <<endl;
Throw (""); 
return false;
return true; }
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.