[C++] POCO Learning Summary (9): Network

[C++] Guo Laoer’s blog post: C++ directory

1. Poco::Net::IPAddress IP address

The Poco::Net::IPAddress class stores IPv4 or IPv6 host addresses.
Poco::Net::IPAddress can be parsed from a string or formatted into a string. Supports IPv4 format (d.d.d.d) and IPv6 format (x: x: x: x: x: x: x: x).

Common functions:
Whether it contains wildcard characters: isWildcard()
Whether it is a broadcast address: isBroadcast()
Whether it is a loopback address: isLoopback()
Whether it is a multicast address: isMulticast()

2. Poco::Net::SocketAddress network address

Poco::Net::SocketAddress combines Poco::Net::IPAddress with a port number to identify the endpoint of the IP network connection.
Poco::Net::SocketAddress supports value semantics, but does not support comparison.
Poco::Net::SocketAddress can be created from an IPAddress + port number, a string IP address + port number, or a colon-separated string of IP address and port number.

3. Poco::Net::DNS domain name

The Poco::Net::DNS class provides an interface to the domain name system, mapping domain names to IP addresses, or from IP addresses to domain names.

4. Poco::Net::HostEntry host information

Poco::Net::HostEntry contains host address information, including host name, alias list, and IP address list.

Example: $ vi host.cpp

#include "Poco/Net/DNS.h"
#include <iostream>

using Poco::Net::DNS;
using Poco::Net::IPAddress;
using Poco::Net::HostEntry;

int main(int argc, char** argv)
{
    
    
	const HostEntry& entry = DNS::hostByName("www.baidu.com");
	std::cout << "Canonical Name: " << entry.name() << std::endl;

	const HostEntry::AliasList& aliases = entry.aliases();
	HostEntry::AliasList::const_iterator it = aliases.begin();
	for (; it != aliases.end(); ++it)
		std::cout << "Alias: " << *it << std::endl;

	const HostEntry::AddressList& addrs = entry.addresses();
	HostEntry::AddressList::const_iterator ita = addrs.begin();
	for (; ita != addrs.end(); ++ita)
		std::cout << "Address: " << ita->toString() << std::endl;
	return 0;
}

Compile:

g++ host.cpp -I ~/git/poco/install/include -L ~/git/poco/install/lib -lPocoNet -std=c++11

Output:

Canonical Name: www.baidu.com
Address: 39.156.66.14
Address: 39.156.66.18
Address: 2409:8c00:6c21:104f:0:ff:b03f:3ae	
Address: 2409:8c00:6c21:1051:0:ff:b0af:279a

5. Poco::Net::Socket socket

Poco::Net::Socket is the base class of various Sockets.

Support common socket interfaces:

  • select() and poll()
  • Set and get various socket options (timeouts, buffer sizes, reuse address flags, etc.)
  • Get socket address and peer address
    Insert image description here

6. Poco::Net::StreamSocket TCP client

Poco::Net::StreamSocket is used to create a TCP connection to the server.
Use sendBytes() and receiveBytes() to send and receive data;
Or use the Poco::Net::SocketStream class, which provides an I /O stream interface.

Example: $ vi tcp.cpp

#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/SocketStream.h"
#include "Poco/StreamCopier.h"
#include <iostream>

int main(int argc, char** argv)
{
    
    
	Poco::Net::SocketAddress sa("www.appinf.com", 80);
	Poco::Net::StreamSocket socket(sa);
	Poco::Net::SocketStream str(socket);
	str << "GET / HTTP/1.1\r\n"
		"Host: www.appinf.com\r\n"
		"\r\n";
		
	str.flush();
	Poco::StreamCopier::copyStream(str, std::cout);
	return 0;
}

Compile:

$ g++ tcp.cpp -I ~/git/poco/install/include -L ~/git/poco/install/lib -lPocoNet -lPocoFoundation

Output:

HTTP/1.1 301 Moved Permanently
Date: Sun, 03 Dec 2023 10:04:01 GMT
Server: Apache
Strict-Transport-Security: max-age=63072000; includeSubdomains;
X-Frame-Options: SAMEORIGIN
Location: https://www.appinf.com/
Content-Length: 295
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="https://www.appinf.com/">here</a>.</p>
<hr>
<address>Apache Server at www.appinf.com Port 80</address>
</body></html>

7. Poco::Net::ServerSocket TCP server

Poco::Net::ServerSocket is used to create a TCP server socket.
Poco::Net::ServerSocket is a lower-level encapsulation. When creating a TCP server, it is recommended to use Poco::Net::TCPServer or the Reactor framework.

Example:

#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/SocketStream.h"
#include "Poco/Net/SocketAddress.h"

int main(int argc, char** argv)
{
    
    
	Poco::Net::ServerSocket srv(8080); 
	for (;;)
	{
    
    
		Poco::Net::StreamSocket ss = srv.acceptConnection();
		Poco::Net::SocketStream str(ss);
		str << "HTTP/1.0 200 OK\r\n"
 			"Content-Type: text/html\r\n"
 			"\r\n"
 			"<html><head><title>My 1st Web Server</title></head>"
 			"<body><h1>Hello, world!</h1></body></html>"
 		<< std::flush;
	}
	return 0;
}

8. Poco::Net::DatagramSocket UDP message

Poco::Net::DatagramSocket is used to send and receive UDP messages.
Poco::Net::MulticastSocket, a subclass of Poco::Net::DatagramSocket, allows sending multicast datagrams.
To receive multicast messages, you must join the multicast group and use MulticastSocket::joinGroup().

Example 1: How to connect udp
$ vi udp-recv.cpp

#include "Poco/Net/DatagramSocket.h"
#include "Poco/Net/SocketAddress.h"
#include <iostream>
int main(int argc, char** argv)
{
    
    
Poco::Net::SocketAddress sa(Poco::Net::IPAddress(), 5514);
Poco::Net::DatagramSocket dgs(sa, false);
char buffer[1024];
	for (;;)
	{
    
    
		Poco::Net::SocketAddress sender;
		int n = dgs.receiveFrom(buffer, sizeof(buffer)-1, sender);
		buffer[n] = '\0';
		std::cout << sender.toString() << ": " << buffer << std::endl;
	}
	return 0;
}

Compile:

g++ -o udp-recv udp-recv.cpp  -I ~/git/poco/install/include -L ~/git/poco/install/lib -lPocoNet -lPocoFoundation

Example 2: udp sender

#include "Poco/Net/DatagramSocket.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Timestamp.h"
#include "Poco/DateTimeFormatter.h"
int main(int argc, char** argv)
{
    
    
	Poco::Net::SocketAddress sa("localhost", 5514);
	Poco::Net::DatagramSocket dgs;
	dgs.connect(sa);
	Poco::Timestamp now;
	std::string msg = Poco::DateTimeFormatter::format(now, "<14>%w %f %H:%M:%S Hello, world!");
	dgs.sendBytes(msg.data(), msg.size());
	return 0;
}

Compile:

g++ -o udp-send udp-send.cpp  -I ~/git/poco/install/include -L ~/git/poco/install/lib -lPocoNet -lPocoFoundation

Run the receiver first and then the sender. The printed information is as follows:

$ ./udp-recv 
127.0.0.1:41406: <14>Tue  5 13:07:54 Hello, world!
127.0.0.1:48117: <14>Tue  5 13:07:56 Hello, world!

9. Poco::Net::TCPServer TCP server framework

Poco::Net::TCPServer implements a multi-threaded TCP server.
1) ServerSocket
The server uses a ServerSocket to accept incoming connections. Before passing the ServerSocket to the TCPServer, it must be put into listening mode.

2) Queue
The server maintains a queue for incoming connections.
A variable number of worker threads get connections from the queue and process them. The number of worker threads automatically adjusts based on the number of connections waiting in the queue.
The number of connections in the queue can be limited
TCPServer creates its own thread that accepts connections and puts them into the queue.

3) Connection TCPServerConnection
TCPServer uses the TCPServerConnection object to handle the connection.
You can use the factory method to create a TCPServerConnection, and the factory object needs to be passed to the TCPServer constructor.

Subclasses of TCPServerConnection must have the run() method. In the run() method, you can handle the logic after the connection.
When run() returns, the TCPServerConnection object will be deleted and the connection will be closed.

Example

#include "Poco/Net/TCPServer.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/NumberParser.h"
#include "Poco/Logger.h"
#include "Poco/Process.h"
#include "Poco/NamedEvent.h"
#include <iostream>

using Poco::Net::TCPServer;
using Poco::Net::TCPServerConnectionFilter;
using Poco::Net::TCPServerConnection;
using Poco::Net::TCPServerConnectionFactory;
using Poco::Net::TCPServerConnectionFactoryImpl;
using Poco::Net::StreamSocket;
using Poco::UInt16;
using Poco::NumberParser;
using Poco::Logger;
using Poco::Event;
using Poco::NamedEvent;
using Poco::Process;
using Poco::ProcessImpl;
using Poco::Exception;

namespace
{
    
    
	class ClientConnection: public TCPServerConnection
	{
    
    
	public:
		ClientConnection(const StreamSocket& s): TCPServerConnection(s){
    
    }

		void run()
		{
    
    
			StreamSocket& ss = socket();
			char buffer[256];
			int n = ss.receiveBytes(buffer, sizeof(buffer));
			while (n > 0)
			{
    
    
				std::cout << "Received " << n << " bytes:" << std::endl;
				std::string msg;
				Logger::formatDump(msg, buffer, n);
				std::cout << msg << std::endl;
				n = ss.receiveBytes(buffer, sizeof(buffer));
			}
		}
	};

	typedef TCPServerConnectionFactoryImpl<ClientConnection> TCPFactory;
	Event terminator;
}


int main(int argc, char** argv)
{
    
    
	Poco::UInt16 port = NumberParser::parse((argc > 1) ? argv[1] : "2001");
	TCPServer srv(new TCPFactory(), port);
	srv.start();
	std::cout << "TCP server listening on port " << port << '.'
		 << std::endl << "Press Ctrl-C to quit." << std::endl;
	terminator.wait();
	return 0;
}

10. Poco::Net::SocketReactor reactor framework

The Reactor framework is based on the Reactor design pattern.
It is a combination of non-blocking sockets and select() with NotificationCenter.
Poco::Net::SocketReactor observes the status of any number of sockets, And send notifications when the socket's state changes (becomes readable, writable, or an error occurs).

Use the Poco::Net::SocketReactor class to register a socket and a callback function.
SocketReactor is used together with SocketAcceptor. SocketAcceptor waits for incoming connections.
When a new connection request arrives, SocketAcceptor accepts the connection and creates a new ServiceHandler object to handle the connection.
When the ServiceHandler finishes processing the connection, it must delete itself

11、HTTPServer

POCO contains a ready-made HTTP server framework

  • Multithreading
  • HTTP 1.0/1.1
  • Certification support
  • cookie support
  • Access HTTPS using NetSSL library

Simple example:

#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "RootHandler.h"
#include "DataHandler.h"
class MyRequestHandlerFactory: public

Poco::Net::HTTPRequestHandlerFactory 
{
    
     
public: 
	MyRequestHandlerFactory() {
    
    }
	Poco::Net::HTTPRequestHandler* createRequestHandler(
	const Poco::Net::HTTPServerRequest& request)
	{
    
    
		if (request.getURI() == "/") 
			return new RootHandler(); 
		else 
			return new DataHandler(); 
	} 
};

int main(int argc, char** argv)
{
    
    
	Poco::UInt16 port = 9999; 
	HTTPServerParams* pParams = new HTTPServerParams; 
	pParams->setMaxQueued(100); 
	pParams->setMaxThreads(16); 
	ServerSocket svs(port);
	HTTPServer srv(new MyRequestHandlerFactory(), svs, pParams);  
	srv.start(); 
	waitForTerminationRequest(); 
	srv.stop();
}

Common categories:

Poco::Net::HTTPClientSession
Poco::Net::HTTPStreamFactory
Poco::Net::HTMLForm
Poco::Net::HTTPCookie
Poco::Net::HTTPRequest
Poco::Net::HTTPResponse

Guess you like

Origin blog.csdn.net/u010168781/article/details/134766792