Example Server Setup

The example code demonstrates how to configure a server, manage WebSocket connections, and define routing for both web and socket requests.

WebApp Package: Example Server Setup

Home documentation

This documentation provides a step-by-step guide on how to set up and start a server using the WebApp package. The example code demonstrates how to configure a server, manage WebSocket connections, and define routing for both web and socket requests.

Prerequisites

Before you begin, ensure you have the following installed on your system:

  • Dart SDK
  • WebApp package (installed via dart pub add webapp)

Example Code Overview

The example code provided below configures a Dart server using the WebApp package. It includes WebSocket management and routing for handling HTTP and WebSocket requests.

Import Necessary Packages

import 'package:webapp/wa_console.dart';
import 'package:webapp/wa_server.dart';
import 'package:webapp/wa_tools.dart';
import 'route/socket_route.dart';
import 'route/web_route.dart';

These imports bring in essential components from the WebApp package, including server management, console output, and utility tools. Additionally, the socket_route.dart and web_route.dart files define routing logic for your application.

Configure Server Settings

WaConfigs configs = WaConfigs(
  widgetsPath: pathTo("./example/widgets"),
  widgetsType: 'j2.html',
  languagePath: pathTo('./example/languages'),
  port: 8085,
  dbConfig: WaDBConfig(enable: false),
  publicDir: pathTo('./example/public'),
);
  • widgetsPath: Specifies the directory where frontend widgets are stored.
  • widgetsType: Defines the file type for widgets (e.g., HTML templates).
  • languagePath: Points to the directory containing language files for internationalization.
  • port: Sets the port number where the server will listen for incoming requests (default is 8085).
  • dbConfig: Configures the database settings. In this example, MongoDB is disabled.
  • publicDir: Specifies the directory for serving static files like images, CSS, and JavaScript.

Initialize the Server

WaServer server = WaServer(configs: configs);

This line initializes the server with the configuration settings defined earlier.

Manage WebSocket Connections

final socketManager = SocketManager(
  server,
  event: SocketEvent(
    onConnect: (socket) {
      server.socketManager?.sendToAll(
        "New user connected! count: ${server.socketManager?.countClients}",
        path: "output",
      );
      socket.send(
        {'message': 'Success connect to socket!'},
        path: 'connected',
      );
    },
    onMessage: (socket, data) {},
    onDisconnect: (socket) {
      var count = server.socketManager?.countClients ?? 0;
      server.socketManager?.sendToAll(
        "User disconnected! count: ${count - 1}",
        path: "output",
      );
    },
  ),
  routes: getSocketRoute(),
);
  • SocketManager: Manages WebSocket connections, allowing real-time communication between clients and the server.
  • onConnect: Triggered when a new client connects. It sends a message to all connected clients and an individual welcome message to the newly connected client.
  • onMessage: Handles incoming messages from clients.
  • onDisconnect: Handles client disconnections, updating the connected client count and notifying all remaining clients.

Define Routing

void main() async {
  server.addRouting(getWebRoute);
  server.start().then((value) {
    Console.p("Example app started: http://localhost:${value.port}");
  });
}
  • addRouting: Adds web routes to the server using the getWebRoute function, which is defined in the web_route.dart file.
  • start: Starts the server and outputs the URL where the application can be accessed (http://localhost:8085 in this case).

Running the Server

To start the server, run the main.dart file in your Dart project:

dart run main.dart

After the server starts, you will see the following output in the console:

Example app started: http://localhost:8085

You can now visit http://localhost:8085 in your browser to interact with the web application.

Conclusion

This example demonstrates how to configure and start a web server using the WebApp package, complete with WebSocket support and custom routing. By following these steps, you can build scalable and interactive web applications in Dart. For more advanced features, explore the WebApp package documentation and experiment with additional configurations.