Home / Downloads / Base libraries / Help
Example how to use Socket Pool
#include
#include "sockaccess.h"
#include
class ter_socket_client : public terimber_socket_client
{
public:
ter_socket_client(terimber_socket_pool* sp) : _sp(sp), _count_send(0), _count_recv(0)
{
}
~ter_socket_client()
{
}
// pool will call function after error occured
virtual void v_on_error(size_t handle, int err, const char* reason)
{
}
// pool will call function after successful sending buffer to socket
virtual void v_on_send(size_t handle, void* buf, size_t requested, size_t processed)
{
++_count_send;
}
// pool will call function after successful receiving buffer from socket
virtual void v_on_receive(size_t handle, void* buf, size_t requested, size_t processed)
{
++_count_recv;
_sp->receive(handle, this, _buf1, 128, -1);
_sp->send(handle, this, _buf, 128, -1);
}
// pool will call function after successful accepting the new incomming connection
virtual void v_on_accept(size_t handle, size_t handle_accepted)
{
// we are responsable to close handle later
_handle_accepted = handle_accepted;
_sp->receive(handle_accepted, this, _buf1, 128, -1);
}
public:
ub1_t _buf[128];
ub1_t _buf1[128];
size_t _count_send;
size_t _count_recv;
size_t _handle_accepted;
private:
terimber_socket_pool* _sp;
};
int main()
{
terimber_socket_pool_access sock_acc;
terimber_socket_pool* sp = sock_acc.get_socket_pool(2, 10000);
ter_socket_client sock_cl(sp);
size_t handle1 = sp->create();
int err = sp->listen(handle1, &sock_cl, 3333, 10);
size_t handle2 = sp->create();
err = sp->connect(handle2, &sock_cl, "localhost", 3333, -1);
sp->receive(handle2, &sock_cl, sock_cl._buf1, 128, -1);
sp->send(handle2, &sock_cl, sock_cl._buf, 128, -1);
// let sockets play a little bit
Sleep(3000);
sp->close(handle1);
sp->close(handle2);
sp->close(sock_cl._handle_accepted);
delete sp;
// print results
printf("sent %d time, received %d times\r\n", sock_cl._count_send, sock_cl._count_recv);
return 0;
}
|
|