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);
{
std::cout <<
"Connected: " << client.
getId() <<
"->" << client.
connect().getPeerId() << std::endl;
clientStream << "12345" << std::flush;
clientStream.clear();
std::string response;
clientStream >> response;
std::cout << "Response: \"" << response << "\"" << std::endl;
}
{
std::cout <<
"Listening: " << server.
bind().listen().getId() << 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::Socket *) new
UI::Util::INetSocket(inHost, inPort, true, true));
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
int getFd() const
Get file descriptor.
Definition File.cpp:164
Mutex Lock class; an object of this class will guard a scope.
Definition Misc.hpp:182
Socket abstraction.
Definition Socket.hpp:36
std::string getId(bool const &peer=false) const
Get human-readable id string.
Definition Socket.cpp:79
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
Namespace for any Schlund+Partner C++ code.
Definition auto_ptr_compat.hpp:16