これは、パフォーマンスと使いやすさの両方を備えたC++ NIOネットワークライブラリです。 C++14以上をサポートし、3つの主要な主流プラットフォームにまたがっています。
基礎となるIOモデルは、Muduoネットワークライブラリのone loop per threadを借用しています。これにより、スレッドセーフAPIカプセル化がより効率的かつシンプルになります。
上層層によって提供されるAPIインターフェイスは、BytedanceのオープンソースGO言語NIOネットワークライブラリNetpollから借用し、 ListenerとDialerを抽象化して、 EventLoopを通じて最終的にサービスを提供します。
このライブラリの使用方法については、クイックスタートを確認できます。
特定の使用例については、例をご覧ください。
すでにサポートされています:
windows/linux/macosプラットフォームは、プラットフォームの最高のパフォーマンスマルチプレックス実装(IOCPが実装するEpoll/epoll/Kqueue)を使用して実装されています。EventLoopを組み合わせて非同期呼び出しを実装します。オペレーティングシステムがsendfileコールをサポートしている場合、C標準ライブラリを呼び出す代わりにゼロコピーコールが呼び出されます。echoサーバーを書きたい場合は、次のコードのみが必要です。 struct server
{
NETPOLL_TCP_MESSAGE (conn, buffer){conn-> send (buffer-> readAll ());}
};
int main ()
{
auto loop = netpoll::NewEventLoop ();
auto listener = netpoll::tcp::Listener::New ({ 6666 });
listener. bind <server>();
loop. serve (listener);
}100^8sなど、 100*8byteだけが必要です)。詳細については、ブログ:詳細な紹介を確認できます。one loop per threadモデルに非常によく一致するだけです。Lockfree_queuefutureを返します。 netpoll::SignalTask::Register ({SIGINT,SIGTERM});
netpoll::SignalTask::Add ([](){
// do something
});将来それをサポートします:
パフォーマンスは非常に高く、私は一時的にASIO(C ++)/Netty(Java)/NetPoll(GO言語)をテストしました。
WindowsシステムでASIO/Nettyをテストしましたが、次のチャートテストはLinuxに基づいており、LinuxにJavaプログラムを展開するのがあまり得意ではないため、次のチャートにはNettyのパフォーマンスがありません。
異なる並行性状況下での単一の接続されたエコーサービスの平均遅延は、次のとおりです(AVG):
サーバー側の基礎となるモデルアーキテクチャ:
Listenerカプセル化は、 TcpServerの使用を簡素化します。すべての呼び出しは次のとおりです。
namespace netpoll ::tcp{
class Listener {
template < typename T>
void bind (Args &&...args); // 用于绑定任意类的对应方法到回调
template < typename T>
std::shared_ptr<T> instance () // 返回内部帮你创建的实例
static Listener New( const InetAddress &address,
const StringView &name = " tcp_listener " ,
bool reUseAddr = true , bool reUsePort = true ); // 建立Listener实例
void enableKickoffIdle ( size_t timeout); // 用于开启剔除空闲连接
}
}Dialerカプセル化により、 TcpClientの使用が簡素化され、使用される呼び出しは次のとおりです。
namespace netpoll ::tcp{
class Dialer {
template < typename T>
void bind (Args &&...args); // 用于绑定任意类的对应方法到回调
template < typename T>
std::shared_ptr<T> instance () // 返回内部帮你创建的实例
static Dialer New( const InetAddress &address,
const StringView &name = " tcp_dialer " ); // 建立Listener实例
void enableRetry (); // 在连接失败后重试
// 以下调用方均是为了在没有C++17的if constexpr情况下的替代品,否则应该直接使用bind
template < typename T, typename ... Args>
static std::shared_ptr<T> Register (Args &&...args);
void onMessage (netpoll::RecvMessageCallback const &cb);
void onConnection (netpoll::ConnectionCallback const &cb);
void onConnectionError (netpoll::ConnectionErrorCallback const &cb);
void onWriteComplete (netpoll::WriteCompleteCallback const &cb);
}
} EventLoopのロードバランシング戦略には個別の設定はなく、すべてRound Robinを使用しています。
EventLoopに関連するAPIは次のとおりです。
NewEventLoop(size_t threadNum=2,const netpoll::StringView&name="eventloop") :eventloopインスタンスを作成し、eventloopのスレッド数を設定します。
serveメソッド:ダイヤラーまたはリスナーを新しく終了した後、この方法を通じてサービスを提供できます。
serveAsDaemonメソッド:効果はサーブメソッドと同じですが、新しいスレッドを開くと現在のスレッドはブロックされません。
enableQuitメソッド:アクティブコールをループエグジットメソッドに許可します。デフォルトでは、すべてのループスレッドをアクティブに終了することはできず、 QuitAllEventLoopメソッドと組み合わせて使用されます。
QuitAllEventLoopメソッド:すべてのループを終了します。
MessageBufferは、カーネルバッファーデータを読み書きするための中間キャッシュです。実際には可変バッファーであり、実装も非常に簡単です。さまざまな種類のバッファー実装については、私の記事:可変長さと不変の長さのバッファの実装を確認できます
ここではさまざまな電話については説明しません。知りたい場合は、対応するヘッダーファイル、NetPoll/util/message_buffer.hを直接確認できます。
このバッファーを実装するハイライトについて簡単に話しましょう。
拡大するとき、サイズ変更の副作用を回避すると、メモリの開口部とコピー操作を簡素化することもできます。
void MessageBuffer::ensureWritableBytes ( size_t len)
{
if ( writableBytes () >= len) return ;
// move readable bytes
if (m_head + writableBytes () >= (len + kBufferOffset ))
{
std::copy ( begin () + m_head, begin () + m_tail, begin () + kBufferOffset );
m_tail = kBufferOffset + (m_tail - m_head);
m_head = kBufferOffset ;
return ;
}
// create new buffer
size_t newLen;
if ((m_buffer. size () * 2 ) > ( kBufferOffset + readableBytes () + len))
newLen = m_buffer. size () * 2 ;
else newLen = kBufferOffset + readableBytes () + len;
// Avoid the inefficiency of using resize
MessageBuffer newbuffer (newLen);
newbuffer. pushBack (* this );
swap (newbuffer);
}対応するFD読み取りバッファーのデータをメッセージバッファーに読み取るREADFDメソッドを提供します。コンテンツは毎回読み取ります。たとえば、MessageBuffer Writable領域が8kb未満の場合、8kbの代替読み取りキャッシュが有効になります。
ssize_t MessageBuffer::readFd ( int fd, int *retErrno)
{
char extBuffer[ 8192 ];
struct iovec vec[ 2 ];
size_t writable = writableBytes ();
vec[ 0 ]. iov_base = begin () + m_tail;
vec[ 0 ]. iov_len = static_cast < int >(writable);
vec[ 1 ]. iov_base = extBuffer;
vec[ 1 ]. iov_len = sizeof (extBuffer);
const int iovcnt = (writable < sizeof extBuffer) ? 2 : 1 ;
ssize_t n = :: readv (fd, vec, iovcnt);
if (n < 0 ) { *retErrno = errno; }
else if ( static_cast < size_t >(n) <= writable) { m_tail += n; }
else
{
m_tail = m_buffer. size ();
pushBack ({extBuffer, n - writable});
}
return n;
}TCPConnectionクラスは、使用時にスマートポインターを通じて使用される抽象クラスです。
このインターフェイスは、次の機能を指定します。
データを送信します(文字列/バッファ/ファイル/ストリームを含む)。
/* *
* @brief Send some data to the peer.
*
* @param msg
* @param len
*/
virtual void send (StringView const &msg) = 0;
virtual void send ( const MessageBuffer &buffer) = 0;
virtual void send (MessageBuffer &&buffer) = 0;
virtual void send ( const std::shared_ptr<MessageBuffer> &msgPtr) = 0;
/* *
* @brief Send a file to the peer.
*
* @param fileName in UTF-8
* @param offset
* @param length
*/
virtual void sendFile (StringView const &fileName, size_t offset = 0 ,
size_t length = 0 ) = 0;
/* *
* @brief Send a stream to the peer.
*
* @param callback function to retrieve the stream data (stream ends when a
* zero size is returned) the callback will be called with nullptr when the
* send is finished/interrupted, so that it cleans up any internal data (ex:
* close file).
* @warning The buffer size should be >= 10 to allow http chunked-encoding
* data stream
*/
// (buffer, buffer size) -> size
// of data put in buffer
virtual void sendStream (
std::function<std:: size_t ( char *, std:: size_t )> callback) = 0;アドレス情報や接続ステータス、またはデータを受信するバッファなどの接続情報を取得します。
/* *
* @brief New the local address of the connection.
*
* @return const InetAddress&
*/
virtual const InetAddress & localAddr () const = 0;
/* *
* @brief New the remote address of the connection.
*
* @return const InetAddress&
*/
virtual const InetAddress & peerAddr () const = 0;
/* *
* @brief Return true if the connection is established.
*
* @return true
* @return false
*/
virtual bool connected () const = 0;
/* *
* @brief Return false if the connection is established.
*
* @return true
* @return false
*/
virtual bool disconnected () const = 0;
/* *
* @brief New the buffer in which the received data stored.
*
* @return MsgBuffer*
*/
virtual MessageBuffer * getRecvBuffer () = 0;接続コールバックまたはステータスを設定します(切断またはtcpnodelay/keepAliveを設定します)。
/* *
* @brief Set the high water mark callback
*
* @param cb The callback is called when the data in sending buffer is
* larger than the water mark.
* @param markLen The water mark in bytes.
*/
virtual void setHighWaterMarkCallback ( const HighWaterMarkCallback &cb,
size_t markLen) = 0;
/* *
* @brief Set the TCP_NODELAY option to the socket.
*
* @param on
*/
virtual void setTcpNoDelay ( bool on) = 0;
/* *
* @brief Shutdown the connection.
* @note This method only closes the writing direction.
*/
virtual void shutdown () = 0;
/* *
* @brief Close the connection forcefully.
*
*/
virtual void forceClose () = 0;
/* *
* @brief Call this method to avoid being kicked off by TcpServer, refer to
* the kickoffIdleConnections method in the TcpServer class.
*
*/
virtual void keepAlive () = 0;
/* *
* @brief Return true if the keepAlive() method is called.
*
* @return true
* @return false
*/
virtual bool isKeepAlive () = 0;接続のコンテキストを設定して、接続の専用ビジネスロジックを処理します。
/* *
* @brief Set the custom data on the connection.
*
* @param context
*/
void setContext ( const Any &context) { m_context = context; }
void setContext (Any &&context) { m_context = std::move (context); }
/* *
* @brief New mutable context
*
* @return Any
*/
Any & getContextRefMut () { return m_context; }
/* *
* @brief New unmutable context
*
* @return Any
*/
Any const & getContextRef () const { return m_context; }
/* *
* @brief Return true if the custom data is set by user.
*
* @return true
* @return false
*/
bool hasContext () const
{
# if __cplusplus >= 201703L
return m_context. has_value ();
# else
return m_context. empty ();
# endif
}
/* *
* @brief Clear the custom data.
*
*/
void clearContext ()
{
# if __cplusplus >= 201703L
m_context. reset ();
# else
m_context. clear ();
# endif
}接続は、データによって送信および受信されたデータの量を蓄積します。
/* *
* @brief Return the number of bytes sent
*
* @return size_t
*/
virtual size_t bytesSent () const = 0;
/* *
* @brief Return the number of bytes received.
*
* @return size_t
*/
virtual size_t bytesReceived () const = 0;この接続に対応するループを取得します。
/* *
* @brief New the event loop in which the connection I/O is handled.
*
* @return EventLoop*
*/
virtual EventLoop * getLoop () = 0;次の2つのユースケースが一時的に提供されます。