Example program for socket / socket streams implementation. Should be installed as ui-utilcpp-echoserver along with the library.
#include "config.h"
#include <string>
#include <memory>
#include <iostream>
#include <exception>
#include <cassert>
std::string const unSock("/tmp/ui-utilcpp-echoserver.sock");
std::string const inHost("localhost");
unsigned int const inPort(9999);
{
clientStream << "12345" << std::flush;
clientStream.clear();
std::string response;
clientStream >> response;
std::cout << "Response: \"" << response << "\"" << std::endl;
}
{
std::cout << "Echoing first 5 bytes on each connect." << std::endl;
while (1)
{
assert(connection.getFd() != -1);
std::cout << "Connection: " << connection.getId() << "<-" << connection.getPeerId() << " (setting snd/rcv timeout on connections 5 seconds)" << std::endl;
connection.
setRcvTimeout(5).
setSndTimeout(5);
char line[6];
stream.read(line, 5);
assert(stream.gcount() == 5);
line[5] = '\0';
std::cout << "ECHOING: " << line << std::endl;
stream.write(line, 5);
}
}
int main(int argc, char *argv[])
{
try
{
UI::Util::auto_ptr<UI::Util::Socket> socket((std::strcmp(argv[1], "unix") == 0) ?
std::strcmp(argv[2], "server") == 0 ? server(*socket.get()) : client(*socket.get());
}
catch (std::exception const & e)
{
std::cerr << "Error: " << e.what() << "." << std::endl;
std::cerr << "Usage: ui-utilcpp-echoserver inet|unix client|server" << std::endl;
return 1;
}
return 0;
}
Socket, descriptors and sockets.
Thread, descriptors and sockets.
Generic exception class for namespace UI.
Definition: Exception.hpp:99
IO stream for file descriptors.
Definition: Socket.hpp:228
int getFd() const
Get file descriptor.
Definition: File.cpp:164
INet Socket.
Definition: Socket.hpp:111
Socket abstraction.
Definition: Socket.hpp:36
std::string getId(bool const &peer=false) const
Get human-readable id string.
Definition: Socket.cpp:79
Socket & listen(int backlog=16)
Start listening.
Definition: Socket.cpp:147
std::string getPeerId() const
Get peer id.
Definition: Socket.cpp:98
virtual Socket & bind()
Bind this socket.
Definition: Socket.cpp:137
virtual Socket & connect()
Connect this socket.
Definition: Socket.cpp:142
int accept(long int toSeconds=0, long int toMicroSeconds=0)
Accept an incoming socket connection.
Definition: Socket.cpp:160
Unix Socket.
Definition: Socket.hpp:130