 ~Sockets~
|
C++ Socket library tutorial
|
|
Connection pooling test
This is a small program to test connection pooling.
It consists of a small SocketHandler class (MyHandler) with a "quit" function
and a socket list method added,
and a server class (OrderSocket).
Commands are "get <url>", "list" sockets, "quit" session, and "stop" server.
pooltest.cpp
#include <StdoutLog.h>
#include <SocketHandler.h>
#include <TcpSocket.h>
#include <ListenSocket.h>
#include <Utility.h>
#include <Parse.h>
#include <HttpGetSocket.h>
#include <PoolSocket.h>
class MyHandler : public SocketHandler
{
public:
MyHandler(StdLog *p) : SocketHandler(p),m_quit(false) {}
~MyHandler() {}
void List(TcpSocket *p) {
for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++)
{
Socket *p0 = (*it).second;
if (dynamic_cast<PoolSocket *>(p0))
{
p -> Send("PoolSocket\n");
}
else
if (dynamic_cast<HttpGetSocket *>(p0))
{
p -> Send("HttpGetSocket\n");
}
else
if (dynamic_cast<TcpSocket *>(p0))
{
p -> Send("TcpSocket\n");
}
else
{
p -> Send("Some kind of Socket\n");
}
}
}
void SetQuit() { m_quit = true; }
bool Quit() { return m_quit; }
private:
bool m_quit;
};
class OrderSocket : public TcpSocket
{
public:
OrderSocket(ISocketHandler& h) : TcpSocket(h) {
SetLineProtocol();
}
void OnAccept() {
Send("Cmd (get,quit,list,stop)>");
}
void OnLine(const std::string& line) {
Parse pa(line);
std::string cmd = pa.getword();
std::string arg = pa.getrest();
if (cmd == "get")
{
HttpGetSocket *p = new HttpGetSocket(Handler(), arg, "tmpfile.html");
p -> SetHttpVersion("HTTP/1.1");
p -> AddResponseHeader("Connection", "keep-alive");
Handler().Add( p );
p -> SetDeleteByHandler();
Send("Reading url '" + arg + "'\n");
}
else
if (cmd == "quit")
{
Send("Goodbye!\n");
SetCloseAndDelete();
}
else
if (cmd == "list")
{
static_cast<MyHandler&>(Handler()).List( this );
}
else
if (cmd == "stop")
{
static_cast<MyHandler&>(Handler()).SetQuit();
}
else
{
Send("Huh?\n");
}
Send("Cmd>");
}
};
int main()
{
StdoutLog log;
MyHandler h(&log);
// line server
ListenSocket<OrderSocket> l3(h);
l3.Bind(1026);
h.Add(&l3);
h.Select(1, 0);
while (!h.Quit())
{
h.Select(1,0);
}
}
|
|
|