1 TCPServer 框架概述

POCO 库提供TCPServer框架,用以搭建自定义的 TCP 服务器。TCPServer维护一个连接队列、一个连接线程池。连接线程用于处理连接,连接线程只要一空闲就不断地从连接队列中取连接并进行处理。一旦连接线程从连接队列中取到一个连接,就会创建一个TCPServerConnection连接对象,并且调用该对象的start()方法,直到start()方法返回,这个连接对象就被删除了。

连接线程的数量是动态的,其取决于连接队列中排队的连接数。当然,你使用的时候可以设定连接队列的最大容量,以防止在高并发应用的服务器上出现连接太多而使连接队列溢出的悲剧发生。当连接队列满了,却还有新的连接到来时,新来的连接就会被立即悄无声息地关闭。

现在我们总结一下,就是要有一个可运行的 TCP 服务应用程序(命名为PoechantTCPServer),还有很多 TCP 连接(命名为PoechantTCPConnection)。而这里我们用到工厂模式(准确说是TCPServerConnectionFactory要我们用的),所以还有一个 PoechantTCPConnectionFactory

2 光说不练假把式

2.1 创建一个 PoechantTCPServer

或许你还不熟悉 POCO 中的 Application,没关系,这不影响本文的叙述。下面先创建一个 ServerApplication 如下:

// PoechantTCPServer.h

#ifndef POECHANT_TCP_SERVER
#define POECHANT_TCP_SERVER #include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Application.h" using Poco::Util::ServerApplication;
using Poco::Util::Application; class PoechantTCPServer: public ServerApplication
{
public:
PoechantTCPServer() {}
~PoechantTCPServer() {}
protected:
void initialize(Application& self);
void uninitialize();
int main(const std::vector<std::string>& args)
}; #endif

这样在调用启动PoechantTCPServer时,会先调用initialize,然后调用main,在main结束后会调用uninitialize。其实现很简单:

// PoechantTCPServer.cpp

#include "PoechantTCPServer.h"

void PoechantTCPServer::initialize(Application& self)
{
ServerApplication::loadConfiguration();
ServerApplication::initialize(self);
} void PoechantTCPServer::uninitialize()
{
ServerApplication::uninitialize();
} int PoechantTCPServer::main(const std::vector<std::string>& args)
{
// 这个咱最后说 return Application::EXIT_OK;
}

2.2 PoechantTCPConnection

连接类的定义很简单,构造函数要传入一个 StreamSocket 和其他你需要的参数。

// PoechantTCPConnection.h

#ifndef POECHANT_TCP_CONNECTION_H
#define POECHANT_TCP_CONNECTION_H #include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/StreamSocket.h"
#include <string> class PoechantTCPConnection: public TCPServerConnection
{
public:
PoechantTCPConnection(const StreamSocket& s,
const std::string& arg1,
int arg2,
double arg3); void run();
private: std::string _arg1;
int _arg2;
double _arg3;
}; #endif

实现如下:

// PoechantTCPConnection.cpp

#include "PoechantTCPConnection.h"
#include "Poco/Util/Application"
#include "Poco/Timestamp.h"
#include "Poco/Exception.h"
#include "Poco/DateTimeFormatter.h" PoechantTCPConnection(const StreamSocket& s, const std::string& arg1, int arg2, double arg3):
TCPServerConnection(s), _arg1(arg1), _arg2(arg2), _arg3(arg3)
{
}
void run()
{
Application& app = Application::instance();
// 日志输出连接的TCP用户的地址(IP和端口)
app.logger().information("Request from " + this->socket().peerAddress().toString());
try
{
// 向客户端发送数据,这里以发送一个表示时间的字符串为例
Timestamp now;
std::string dt(DateTimeFormatter::format(now, _format));
dt.append("\r\n");
socket().sendBytes(dt.data(), (int) dt.length());
}
catch (Poco::Exception& e)
{
app.logger().log(e);
}
}

2.3 PoechantTCPConnectionFactory

工厂模式不必多说,名字唬人,其实非常非常简单(准确的说设计模式大部分名字都唬人,但大部分都很有用,设计模式本身并不牛B,能把设计模式抽象提炼出来成我们现在认为很简单的这些模式的那几个人很牛B)。具体如下:

// PoechantTCPConnectionFactory.h

#ifndef POECHANT_TCP_CONNECTION_FACTORY_H
#define POECHANT_TCP_CONNECTION_FACTORY_H #include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/StreamSocket.h"
#include <string> class PoechantTCPConnectionFactory: public TCPServerConnectionFactory
{
public:
PoechantTCPConnectionFactory(const std::string arg1, int arg2, double arg3)
: _arg1(arg1), _arg2(arg2), _arg3(arg3)
{
} TCPServerConnection* createConnection(const StreamSocket& socket)
{
return new PoechantTCPConnection(socket, arg1, arg2, arg3);
} private:
std::string arg1;
int arg2;
double arg3;
}; #endif

2.4 启动

回头来说PoechantTCPServer::main(const std::vector<std::string>& args),其过程就是创建一个绑定了地址的ServerSocket,把它传给TCPServer,当然别忘了把工程对象也给你的TCPServer传一个。最后就start()waitForTerminationRequeststop()就行了。

int PoechantTCPServer::main(const std::vector<std::string>& args)
{
unsigned short port = (unsigned short) config().getInt("PoechantTCPServer.port", 12346);
std::string format(config().getString("PoechantTCPServer.format",
DateTimeFormat::ISO8601_FORMAT)); // 1. Bind a ServerSocket with an address
ServerSocket serverSocket(port); // 2. Pass the ServerSocket to a TCPServer
TCPServer server(new PoechantTCPConnectionFactory(format), serverSocket); // 3. Start the TCPServer
server.start(); // 4. Wait for termination
waitForTerminationRequest(); // 5. Stop the TCPServer
server.stop(); return Application::EXIT_OK;
}

然后写一个程序入口:

#include "PoechantTCPServer.h"

int main(int argc, char **argv)
{
return PoechantTCPServer().run(argc, argv);
}

3 写一个 Client 测测

TCPServer 要用 TCP 的客户端来测试。在 POCO 中有丰富的 Socket,其中 TCP 方式的 Socket 有:

  • Poco::Net::ServerSocket
  • Poco::Net::StreamSocket
  • Poco::Net::DialogSocket
  • Poco::Net::SecureServerSocket
  • Poco::Net::SecureStreamSocket

UDP 方式的 Socket 有:

  • Poco::Net::DatagramSocket
  • Poco::Net::MulticastSocket

一个 TCP 方式 Client 如下(这里用了 while 循环,其实可以在收到数据后就关闭的)

#include <iostream>
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/SocketAddress.h" #define BUFFER_SIZE 1024 using Poco::Net::SocketAddress;
using Poco::Net::StreamSocket; int main (int argc, const char * argv[])
{
SocketAddress address("127.0.0.1", 12346);
StreamSocket socket(address);
char buffer[BUFFER_SIZE];
while (true)
{
if (socket.available())
{
int len = socket.receiveBytes(buffer, BUFFER_SIZE);
buffer[len] = '\0';
std::cout << "" << buffer << std::endl;
}
}
return 0;
}

-

from:Blog.CSDN.net/Poechant

POCO库中文编程参考指南(10)如何使用TCPServer框架?的更多相关文章

  1. POCO库中文编程参考指南(11)如何使用Reactor框架?

    1 Reactor 框架概述 POCO 中的 Reactor 框架是基于 Reactor 设计模式进行设计的.其中由 Handler 将某 Socket 产生的事件,发送到指定的对象的方法上,作为回调 ...

  2. POCO库中文编程参考指南(8)丰富的Socket编程

    POCO库中文编程参考指南(8)丰富的Socket编程 作者:柳大·Poechant 博客:Blog.CSDN.net/Poechant 邮箱:zhongchao.ustc#gmail.com (# ...

  3. POCO库中文编程参考指南(4)Poco::Net::IPAddress

    POCO库中文编程参考指南(4)Poco::Net::IPAddress 作者:柳大·Poechant 博客:Blog.CSDN.net/Poechant 邮箱:zhongchao.ustc#gmai ...

  4. POCO库中文编程参考指南(3)Poco::Net::Socket

    POCO库中文编程参考指南(3)Poco::Net::Socket 作者:柳大·Poechant 博客:Blog.CSDN.net/Poechant 邮箱:zhongchao.ustc#gmail.c ...

  5. POCO库中文编程参考指南(2)基本数据类型(Poco/Types.h)

    POCO库中文编程参考指南(2)基本数据类型 作者:柳大·Poechant 博客:Blog.CSDN.net/Poechant 邮箱:zhongchao.ustc#gmail.com (# -> ...

  6. POCO库中文编程参考指南(1)总览

    POCO库中文编程参考指南(1)总览 作者:柳大·Poechant 博客:Blog.CSDN.net/Poechant 邮箱:zhongchao.ustc#gmail.com (# -> @) ...

  7. POCO库中文编程参考指南(5)Poco::Net::SocketAddress

    1 枚举 最大地址长度,这个与Poco::Net::IPAddress中的定义可以类比,不过这里指的是`struct sockaddr_in6 enum { MAX_ADDRESS_LENGTH = ...

  8. POCO库中文编程参考指南(6)Poco::Timestamp

    1 类型别名 三个时间戳相关的类型别名,TimeDiff表示两个时间戳的差,第二个是以微秒为单位的时间戳,第三个是以 100 纳秒(0.1 微妙)为单位的时间戳: typedef Int64 Time ...

  9. POCO库中文编程参考指南(9)Poco::Net::DNS

    1 Poco::Net::DNS namespace Poco { namespace Net { class Net_API DNS { public: static HostEntry hostB ...

随机推荐

  1. 关于HDFS NFS3的配置

    1.在core-site.xml中配置 <property> <name>hadoop.proxyuser.root.groups</name> <value ...

  2. JS中的call_user_func封装

    PHP常见的call_user_func方法,在JS中有时候会用到,比如你想根据某个动态变量去执行方法. 以前遇到过类似的问题没有解决,现在不太记得具体案例了.今天无意中看到类似文章,学到了.代码如下 ...

  3. 深入Asyncio(七)异步上下文管理器

    Async Context Managers: async with 在某些场景下(如管理网络资源的连接建立.断开),用支持异步的上下文管理器是很方便的. 那么如何理解async with关键字? 先 ...

  4. 初探swift语言的学习笔记四-2(对上一节有些遗留进行处理)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/30314359 转载请注明出处 假设认为文章对你有所帮助,请通过留言 ...

  5. hive job oom问题

    错误信息例如以下:Container [pid=26845,containerID=container_1419056923480_0212_02_000001] is running beyond ...

  6. django框架小技巧

    带命名空间的URL名字 多应用中路由定义,采用命名空间,防止冲突 url(r'^polls/', include('polls.urls', namespace="polls")) ...

  7. 【模板】P3806点分治1

    [模板]P3806 [模板]点分治1 很好的一道模板题,很无脑经典. 讲讲淀粉质吧,很营养,实际上,点分治是树上的分治算法.根据树的特性,树上两点的路径只有一下两种情况: 路径经过根\((*)\) 路 ...

  8. 我的Android进阶之旅------>使用ThumbnailUtils类获取视频的缩略图

    今天看了一段代码,是关于获取视频的缩略图的,让我认识了一个ThumbnailUtils类,代码如下. Bitmap bitmap = ThumbnailUtils.createVideoThumbna ...

  9. weblogic开启远程访问的jmx设置

    通过jmx远程访问weblogic获取监控jvm的数据,要在weblogic启动的时候设置一些配置,具体如下: 在weblogic的安装目录:{weblogic_home}/wlserver_10.3 ...

  10. Java for LeetCode 125 Valid Palindrome

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...