Wt  4.11.1
Classes | Public Member Functions | Static Public Member Functions | Related Functions | List of all members
Wt::WServer Class Reference

A class encapsulating a web application server. More...

#include <Wt/WServer.h>

Classes

class  Exception
 Server Exception class. More...
 
class  SessionInfo
 Contains the information for one session. More...
 

Public Member Functions

WTCONNECTOR_API WServer (const std::string &wtApplicationPath=std::string(), const std::string &wtConfigurationFile=std::string())
 Creates a new server instance. More...
 
WTCONNECTOR_API WServer (int argc, char *argv[], const std::string &wtConfigurationFile=std::string())
 Creates a new server instance and configures it. More...
 
WTCONNECTOR_API WServer (const std::string &applicationPath, const std::vector< std::string > &args, const std::string &wtConfigurationFile=std::string())
 Creates a new server instance and configures it. More...
 
virtual WTCONNECTOR_API ~WServer ()
 Destructor. More...
 
WT_API void setIOService (WIOService &ioService)
 Sets the I/O service. More...
 
WT_API WIOServiceioService ()
 Returns the I/O service. More...
 
WTCONNECTOR_API void setServerConfiguration (int argc, char *argv[], const std::string &serverConfigurationFile=std::string())
 Configures the HTTP(S) server or FastCGI process. More...
 
WTCONNECTOR_API void setServerConfiguration (const std::string &applicationPath, const std::vector< std::string > &args, const std::string &serverConfigurationFile=std::string())
 Configures the HTTP(S) server or FastCGI process. More...
 
WT_API void addEntryPoint (EntryPointType type, ApplicationCreator callback, const std::string &path=std::string(), const std::string &favicon=std::string())
 Binds an entry-point to a callback function to create a new application. More...
 
WT_API void addResource (const std::shared_ptr< WResource > &resource, const std::string &path)
 Binds a resource to a fixed path. More...
 
WT_API void addResource (const std::shared_ptr< WWebSocketResource > &resource, const std::string &path)
 Binds a WebSocket resource to a fixed path. More...
 
WT_API void addResource (WResource *resource, const std::string &path)
 Binds a resource to a fixed path. More...
 
WT_API void removeEntryPoint (const std::string &path)
 Removes an entry point. More...
 
WTCONNECTOR_API bool start ()
 Starts the server in the background. More...
 
WTCONNECTOR_API void stop ()
 Stops the server. More...
 
WTCONNECTOR_API bool isRunning () const
 Returns whether the server is running. More...
 
WTCONNECTOR_API void run ()
 Starts the server, waits for shutdown, then stops the server. More...
 
WTCONNECTOR_API void resume ()
 Resumes the server. More...
 
WTCONNECTOR_API int httpPort () const
 Returns the server HTTP port number. More...
 
WT_API std::string appRoot () const
 Returns the approot special property. More...
 
WTCONNECTOR_API std::string docRoot () const
 Returns the docroot (if using wthttp) More...
 
WT_API void post (const std::string &sessionId, const std::function< void()> &function, const std::function< void()> &fallBackFunction=std::function< void()>())
 Posts a function to a session. More...
 
WT_API void postAll (const std::function< void()> &function)
 Posts a function to all currently active sessions. More...
 
WT_API void schedule (std::chrono::steady_clock::duration duration, const std::string &sessionId, const std::function< void()> &function, const std::function< void()> &fallBackFunction=std::function< void()>())
 Schedules a function to be executed in a session. More...
 
WTCONNECTOR_API void setSslPasswordCallback (const SslPasswordCallback &cb)
 Change input method for server certificate passwords (http backend) More...
 
WT_API bool readConfigurationProperty (const std::string &name, std::string &value) const
 Reads a configuration property. More...
 
WT_API void setLocalizedStrings (const std::shared_ptr< WLocalizedStrings > &stringResolver)
 Sets the resource object that provides localized strings. More...
 
WT_API std::shared_ptr< WLocalizedStringslocalizedStrings () const
 Sets the resource object that provides localized strings. More...
 
WTCONNECTOR_API std::vector< SessionInfosessions () const
 Retrieve information on all sessions. More...
 
WT_API WLoggerlogger ()
 Returns the logger instance. More...
 
WT_API void setCustomLogger (const WLogSink &customLogger)
 Sets a custom logger to redirect all logging to. More...
 
WT_API WLogEntry log (const std::string &type) const
 Adds an entry to the log. More...
 
WT_API bool dedicatedSessionProcess () const
 Reflects whether the current process is a dedicated session process. More...
 

Static Public Member Functions

static WServerinstance ()
 Returns the server instance. More...
 
static WT_API int waitForShutdown ()
 Waits for a shutdown signal. More...
 
static WT_API void restart (int argc, char **argv, char **envp)
 A utility method to restart. More...
 
static WT_API void restart (const std::string &applicationPath, const std::vector< std::string > &args)
 A utility method to restart. More...
 

Related Functions

(Note that these are not member functions.)

int WRun (int argc, char **argv, ApplicationCreator createApplication=0)
 Runs the Wt application server. More...
 
int WRun (const std::string &applicationPath, const std::vector< std::string > &args, ApplicationCreator createApplication=0)
 Runs the Wt application server. More...
 

Detailed Description

A class encapsulating a web application server.

This server class represents an instance of an application server.

It offers support for multiple application entry points and control over starting and stopping the server. This may be used as an alternative to using WRun() when you wish to support multiple application entry points, or for integrating a Wt (stand-alone httpd) server application into an existing application, with control over starting and stopping the server as appropriate.

As an example usage, consider the implementation of WRun(), which starts the server until a Ctrl-C is pressed or a termination signal has been received, or a restart is indicated using SIGHUP or a changed binary (argv[0]):

int WRun(int argc, char *argv[], ApplicationCreator createApplication)
{
try {
// use argv[0] as the application name to match a suitable entry
// in the Wt configuration file, and use the default configuration
// file (which defaults to /etc/wt/wt_config.xml unless the environment
// variable WT_CONFIG_XML is set)
WServer server(argv[0]);
// WTHTTP_CONFIGURATION is e.g. "/etc/wt/wthttpd"
server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION);
// add a single entry point, at the default location (as determined
// by the server configuration's deploy-path)
server.addEntryPoint(Wt::EntryPointType::Application, createApplication);
if (server.start()) {
std::cerr << "Shutdown (signal = " << sig << ")" << std::endl;
server.stop();
if (sig == SIGHUP)
WServer::restart(argc, argv, environ);
}
} catch (WServer::Exception& e) {
std::cerr << e.what() << "\n";
return 1;
} catch (std::exception& e) {
std::cerr << "exception: " << e.what() << "\n";
return 1;
}
}
static WT_API void restart(int argc, char **argv, char **envp)
A utility method to restart.
WTCONNECTOR_API WServer(const std::string &wtApplicationPath=std::string(), const std::string &wtConfigurationFile=std::string())
Creates a new server instance.
Definition: WTestEnvironment.C:21
int WRun(int argc, char **argv, ApplicationCreator createApplication=0)
Runs the Wt application server.
static WT_API int waitForShutdown()
Waits for a shutdown signal.
Definition: WServer.C:384
@ Application
Specifies a full-screen application.

Constructor & Destructor Documentation

◆ WServer() [1/3]

Wt::WServer::WServer ( const std::string &  wtApplicationPath = std::string(),
const std::string &  wtConfigurationFile = std::string() 
)

Creates a new server instance.

The wtApplicationPath is used to match specific application-settings in the Wt configuration file. If no specific match could be found, the general settings are used (corresponding to the '*' selector).

The Wt application configuration is read from the wtConfigurationFile. If empty, this defaults to the value configured at build time.

For more information on configuring Wt applications, see Configuration.

Exceptions
Exception: indicates a configuration problem.
See also
setServerConfiguration()

◆ WServer() [2/3]

WTCONNECTOR_API Wt::WServer::WServer ( int  argc,
char *  argv[],
const std::string &  wtConfigurationFile = std::string() 
)

Creates a new server instance and configures it.

This is equivalent to:

WServer server(argv[0]);
server.setServerConfiguration(argc, argv, wtConfigurationFile);
Exceptions
Exception: indicates a configuration problem.
See also
WServer(const std::string&, const std::string&)
setServerConfiguration()

◆ WServer() [3/3]

WTCONNECTOR_API Wt::WServer::WServer ( const std::string &  applicationPath,
const std::vector< std::string > &  args,
const std::string &  wtConfigurationFile = std::string() 
)

Creates a new server instance and configures it.

This is equivalent to:

WServer server(applicationPath);
server.setServerConfiguration(applicationPath, args, wtConfigurationFile);

This version of the WServer constructor takes a std::string for the application path, and a vector of arguments (not including argv[0], the application path) instead of argc and argv, for better convenience when arguments are not provided via the command line.

Exceptions
Exception: indicates a configuration problem.
See also
WServer(const std::string&, const std::string&)
setServerConfiguration()

◆ ~WServer()

Wt::WServer::~WServer ( )
virtual

Destructor.

If the server was still running, it is stopped first by calling stop(). It is probably safer to call stop() first yourself, since this allows exceptions to be caught.

See also
isRunning(), stop()

Member Function Documentation

◆ addEntryPoint()

void Wt::WServer::addEntryPoint ( EntryPointType  type,
ApplicationCreator  callback,
const std::string &  path = std::string(),
const std::string &  favicon = std::string() 
)

Binds an entry-point to a callback function to create a new application.

The path is the local URL at which the application is deployed: when a user visits this URL, the callback will be called to create a new application.

If the path does not start with a slash ('/'), the deployment path will be prepended. The deployment path defaults to '/' but can be overridden in the wthttp connector with the –deploy-path option (see also Built-in httpd configuration). This implies that when the path is empty (the default), it is set to the deployment path.

The optional favicon is a URL path (which should not contain the host part!) to a favicon, which is the icon displayed in the browser for your application. Alternatively, you may specify a favicon using the "favicon" property in the configuration file (see also 10.2 General application settings (wt_config.xml)).

See also
removeEntryPoint()

◆ addResource() [1/3]

void Wt::WServer::addResource ( const std::shared_ptr< WResource > &  resource,
const std::string &  path 
)

Binds a resource to a fixed path.

Resources may either be private to a single session or public. Use this method to add a public resource with a fixed path.

Exceptions
Exceptionif an entrypoint was already registered at the given path
See also
removeEntryPoint()

◆ addResource() [2/3]

void Wt::WServer::addResource ( const std::shared_ptr< WWebSocketResource > &  resource,
const std::string &  path 
)

Binds a WebSocket resource to a fixed path.

This will add a public resource that is deployed on a fixed path. The resource will be accessible to any client that is able to access the server on the path.

Exceptions
Exceptionif an entrypoint was already registered at the given path
See also
removeEntryPoint()

◆ addResource() [3/3]

void Wt::WServer::addResource ( WResource resource,
const std::string &  path 
)

Binds a resource to a fixed path.

Resources may either be private to a single session or public. Use this method to add a public resource with a fixed path.

Note
Ownership of the resource is external to WServer. The resource first needs to be removed (while the server is stopped) before being destroyed, or has to outlive the WServer.
Exceptions
Exceptionif an entrypoint was already registered at the given path
See also
removeEntryPoint()
Deprecated:
Use addResource(const std::shared_ptr<WResource>&, const std::string&) instead.

◆ appRoot()

std::string Wt::WServer::appRoot ( ) const

Returns the approot special property.

See also
WApplication::appRoot()

◆ dedicatedSessionProcess()

bool Wt::WServer::dedicatedSessionProcess ( ) const

Reflects whether the current process is a dedicated session process.

Note
This will only be accurate after the WServer has been configured, either through setServerConfiguration() or one of the constructors that immediately configures the server.

◆ docRoot()

WTCONNECTOR_API std::string Wt::WServer::docRoot ( ) const

Returns the docroot (if using wthttp)

If you're using wthttp, this returns the location passed to the –docroot argument, just like WApplication::docRoot(). This allows access to this parameter outside of the context of a WApplication.

If you're using any other connector, this returns the empty string.

◆ httpPort()

WTCONNECTOR_API int Wt::WServer::httpPort ( ) const

Returns the server HTTP port number.

Returns -1 if the port is not known (i.e. because the connector is not aware of how the http server is configured).

Note
If the server listens on multiple ports, only the first port is returned.

◆ instance()

static WServer* Wt::WServer::instance ( )
static

Returns the server instance.

Returns the single server instance. This may be useful when using WRun(), which does not provide direct access to the instantiated server, but still you want to use functions like post().

Note
When instantiating multiple servers, this will simply return the last instance. You probably want to avoid this function then.

◆ ioService()

WIOService & Wt::WServer::ioService ( )

Returns the I/O service.

See also
setIOService()

◆ isRunning()

WTCONNECTOR_API bool Wt::WServer::isRunning ( ) const

Returns whether the server is running.

See also
start(), stop()

◆ localizedStrings()

std::shared_ptr< WLocalizedStrings > Wt::WServer::localizedStrings ( ) const

Sets the resource object that provides localized strings.

See also
setLocalizedStrings()

◆ log()

WLogEntry Wt::WServer::log ( const std::string &  type) const

Adds an entry to the log.

See also
Wt::log(), WApplication::log()

◆ logger()

WLogger & Wt::WServer::logger ( )

Returns the logger instance.

This is the logger class used in WApplication::log() and Wt::log() functions.

◆ post()

void Wt::WServer::post ( const std::string &  sessionId,
const std::function< void()> &  function,
const std::function< void()> &  fallBackFunction = std::function<void ()>() 
)

Posts a function to a session.

This is a thread-safe method to post a particular event (implemented as a function object) to be run within the context of a session, identified by its WApplication::sessionId(). The method will safely handle the case where the session is being terminated, and the session lock will be taken to execute the function in the context of the session (with WApplication::instance() pointing to the correct application), just as with a request initiated by the browser. You will typically also want to push the changes to the client using server-initiated updates (WApplication::triggerUpdate()).

The method returns immediately, and the function will be run within the thread-pool that handles incoming web requests. In this way, it avoids dead-lock scenarios.

If a fallbackFunction is specified then in case the session is dead, it is called instead.

This provides a good alternative to grabbing the update lock of an application to directly push changes to a session out of its event loop.

Note that if you post an event to a method of a widget (or other object), it may still be that the targeted object has been deleted, if the life-time of that object is not the same as the life-time of the application. It may be useful to protect yourself from this by using WApplication::bind().

◆ postAll()

void Wt::WServer::postAll ( const std::function< void()> &  function)

Posts a function to all currently active sessions.

See also
post()

◆ readConfigurationProperty()

bool Wt::WServer::readConfigurationProperty ( const std::string &  name,
std::string &  value 
) const

Reads a configuration property.

As properties are unique to an executable location, they are defined from the moment that setServerConfiguration() is invoked. Use this method to access configuration properties outside of an active session, e.g. from within the main() function.

See also
WApplication::readConfigurationProperty()

◆ removeEntryPoint()

void Wt::WServer::removeEntryPoint ( const std::string &  path)

Removes an entry point.

Use this method to remove an entry point or static resource.

In a multi-threaded environment, this may only be done when the server is not running.

Note
If the entry point is a resource, the resource will not be deleted
See also
addEntryPoint(), addResource()

◆ restart() [1/2]

void Wt::WServer::restart ( const std::string &  applicationPath,
const std::vector< std::string > &  args 
)
static

A utility method to restart.

This will result the application with the new image (applicationPath), effectively loading a newly deployed version. (Experimental, UNIX only)

This version of restart() takes a std::string for the application path, and a vector of arguments (not including argv[0], the application path) instead of argc and argv, for better convenience when arguments are not provided via the command line.

◆ restart() [2/2]

static WT_API void Wt::WServer::restart ( int  argc,
char **  argv,
char **  envp 
)
static

A utility method to restart.

This will result the application with the new image (argv[0]), effectively loading a newly deployed version. (Experimental, UNIX only)

◆ resume()

WTCONNECTOR_API void Wt::WServer::resume ( )

Resumes the server.

This closes and reopens the listen socket(s) for accepting new TCP and/or SSL connections. This may be needed when the OS (like IPhoneOS) has closed the sockets while suspending the application.

◆ run()

WTCONNECTOR_API void Wt::WServer::run ( )

Starts the server, waits for shutdown, then stops the server.

This is equivalent to:

if (start()) {
stop();
}
WTCONNECTOR_API void stop()
Stops the server.
WTCONNECTOR_API bool start()
Starts the server in the background.
See also
start()
stop()
waitForShutdown()

◆ schedule()

void Wt::WServer::schedule ( std::chrono::steady_clock::duration  duration,
const std::string &  sessionId,
const std::function< void()> &  function,
const std::function< void()> &  fallBackFunction = std::function<void ()>() 
)

Schedules a function to be executed in a session.

The function will run in the session specified by sessionId, after duration. If the session does not exist anymore, fallBackFunction will be executed.

See also
post()

◆ sessions()

WTCONNECTOR_API std::vector<SessionInfo> Wt::WServer::sessions ( ) const

Retrieve information on all sessions.

This is only implemented for the wthttp connector.

If the dedicated process session policy is used, only the original process has access to the full list of sessions. Public resources (those registered with addResource()) run in the original process, so they can access this list.

◆ setCustomLogger()

void Wt::WServer::setCustomLogger ( const WLogSink customLogger)

Sets a custom logger to redirect all logging to.

Instead of using the server's default logger, this will send all logging to some custom WLogSink.

◆ setIOService()

void Wt::WServer::setIOService ( WIOService ioService)

Sets the I/O service.

The server will use an I/O service for scheduling functions into a thread-pool, and to implement asynchronous networking, whose call-back funtions are scheduled in the same thread pool.

By default, a server will create its own I/O service, but you may configure it to reuse another I/O service.

◆ setLocalizedStrings()

void Wt::WServer::setLocalizedStrings ( const std::shared_ptr< WLocalizedStrings > &  stringResolver)

Sets the resource object that provides localized strings.

This is used only for WString::tr() used from within static resources.

The default value is 0.

◆ setServerConfiguration() [1/2]

WTCONNECTOR_API void Wt::WServer::setServerConfiguration ( const std::string &  applicationPath,
const std::vector< std::string > &  args,
const std::string &  serverConfigurationFile = std::string() 
)

Configures the HTTP(S) server or FastCGI process.

Configures the HTTP(S) server using command-line arguments, a configuration file, or both. The valid options are described in Built-in httpd configuration.

The applications themselves are configured using the configuration file passed to the constructor.

The server configuration must be set before any other functionality can be used.

In case of FastCGI deployment, the serverConfigurationFile argument is ignored, and depending on the command-line arguments, this process may become a FastCGI protocol relay process which never returning from this call but directs the FastCGI stream to the correct session, rather than a Wt application server.

This version of setServerConfiguration() takes a std::string for the application path, and a vector of arguments (not including argv[0], the application path) instead of argc and argv, for better convenience when arguments are not provided via the command line.

Exceptions
Exception: indicates a configuration problem.

◆ setServerConfiguration() [2/2]

WTCONNECTOR_API void Wt::WServer::setServerConfiguration ( int  argc,
char *  argv[],
const std::string &  serverConfigurationFile = std::string() 
)

Configures the HTTP(S) server or FastCGI process.

Configures the HTTP(S) server using command-line arguments, a configuration file, or both. The valid options are described in Built-in httpd configuration.

The applications themselves are configured using the configuration file passed to the constructor.

The server configuration must be set before any other functionality can be used.

In case of FastCGI deployment, the serverConfigurationFile argument is ignored, and depending on the command-line arguments, this process may become a FastCGI protocol relay process which never returning from this call but directs the FastCGI stream to the correct session, rather than a Wt application server.

Exceptions
Exception: indicates a configuration problem.

◆ setSslPasswordCallback()

WTCONNECTOR_API void Wt::WServer::setSslPasswordCallback ( const SslPasswordCallback &  cb)

Change input method for server certificate passwords (http backend)

The private server identity key may be protected by a password. If you want to control how the password is retrieved, set a password handler by calling this function. If no password handler is set, the OpenSSL default handler will be used, which asks to enter the password on stdio.

This function must be called before calling start().

The max_length parameter is informational and indicates that the underlying implementation will truncate the password to this length.

◆ start()

WTCONNECTOR_API bool Wt::WServer::start ( )

Starts the server in the background.

Returns whether the server could be successfully started.

Exceptions
Exception: indicates a problem starting the server.
See also
isRunning(), stop()

◆ stop()

WTCONNECTOR_API void Wt::WServer::stop ( )

Stops the server.

All active application sessions are terminated cleanly, and the HTTP(S) server is shut down.

Note
This will also stop the underlying ioService(), and will block until all pending tasks have completed.
Exceptions
Exception: indicates a problem while stopping the server.
See also
isRunning(), start()

◆ waitForShutdown()

int Wt::WServer::waitForShutdown ( )
static

Waits for a shutdown signal.

This static method blocks the current thread, waiting for a shutdown signal. The implementation and details are platform dependent, but this is usually Ctrl-C (SIGINT) or SIGKILL.

This method is convenient if you want to customize how the server is started (by instantiating a WServer object yourself, instead of using Wt::WRun()), but still want to use Wt as a standalone server that cleanly terminates on interruption.

This will also catch SIGHUP, to reread the configuration file.

Friends And Related Function Documentation

◆ WRun() [1/2]

int WRun ( const std::string &  applicationPath,
const std::vector< std::string > &  args,
ApplicationCreator  createApplication = 0 
)
related

Runs the Wt application server.

This function runs the application server, and should be called only once (e.g. from within your main function).

The createApplication parameter is a std::function object that should create a new application instance for a new user visiting the application. It is of type: std::function<Wt::WApplication* (const Wt::WEnvironment&)>, and thus you can pass to it a function like:

Wt::WApplication *createApplication(const Wt::WEnvironment& env)
{
  // ...
}

When using the built-in httpd, the implementation listens for POSIX termination signals (or console CTRL-C) event. You can use the WServer class for more flexible control on starting and stopping the server.

This version of WRun() takes a std::string for the application path, and a vector of arguments (not including argv[0], the application path) instead of argc and argv, for better convenience when arguments are not provided via the command line.

See also
WApplication

◆ WRun() [2/2]

int WRun ( int  argc,
char **  argv,
ApplicationCreator  createApplication = 0 
)
related

Runs the Wt application server.

This function runs the application server, and should be called only once (e.g. from within your main function).

The createApplication parameter is a std::function object that should create a new application instance for a new user visiting the application. It is of type: std::function<Wt::WApplication* (const Wt::WEnvironment&)>, and thus you can pass to it a function like:

Wt::WApplication *createApplication(const Wt::WEnvironment& env)
{
  // ...
}

When using the built-in httpd, the implementation listens for POSIX termination signals (or console CTRL-C) event. You can use the WServer class for more flexible control on starting and stopping the server.

See also
WApplication