TcpListener¶
#include <lthread_cpp/listener.h>
using namespace lthread_cpp::net;
- class TcpListener¶
Member Functions¶
- TcpListener(const std::string& ip, short int port)¶
Initializes TcpListener instance with the ip and port specified.
- void Listen()¶
Binds IP and port to socket.
Throws: SocketException if it fails to bind or listen.
- Socket Accept()¶
Blocks until a new connection is accepted.
Returns: A new Socket object for the new connection. Throws: SocketException if lthread_accept() failed.
- void Close()¶
Closes listening port.
Examples¶
#include <lthread_cpp/lthread.h>
#include <lthread_cpp/socket.h>
#include <lthread_cpp/listener.h>
using namespace lthread_cpp;
using namespace lthread_cpp::net;
void HandleConnection(Socket& s)
{
s.Send("Hi");
}
void Run()
{
TcpListener listener("127.0.0.1", 8090);
listener.Listen();
while (1) {
Socket s = listener.Accept();
Lthread t1 {&HandleConnection, std::move(s)};
t1.Detach();
}
}
int main()
{
Lthread t{&Run};
t.Detach();
Lthread::Run();
}
cc -std=c++11 test.cc -o test -llthread_cpp -llthread -lpthread -lstdc++ && ./test