Example Server Setup

Simple WebApp server example with WebSocket support and routing configuration

Simple WebApp Server Example

This example demonstrates how to set up a basic WebApp server with WebSocket support, routing, and email functionality.

Prerequisites

Before you begin, ensure you have:

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

Basic Server Setup

Here's a complete example of setting up a WebApp server:

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';

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'),
);

Create Server with WebSocket Support

WaServer server = WaServer(configs: configs);

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) {
      // Handle incoming socket messages
    },
    onDisconnect: (socket) {
      var count = server.socketManager?.countClients ?? 0;
      server.socketManager?.sendToAll(
        'User disconnected! count: ${count - 1}',
        path: 'output',
      );
    },
  ),
  routes: getSocketRoute(),
);

Start the Server

void main() async {
  server.addRouting(getWebRoute);
  server.start().then((value) {
    Console.p('Example app started: http://localhost:${value.port}');
  });
}

Configuration Options

  • widgetsPath: Specifies the directory where frontend widgets are stored
  • widgetsType: Defines the file type for widgets (e.g., j2.html templates)
  • languagePath: Points to the directory containing language files for internationalization
  • port: Sets the port number where the server will listen for requests
  • dbConfig: Configures database settings (MongoDB can be enabled/disabled)
  • publicDir: Specifies the directory for serving static files

SMTP Email Example

The WebApp package also supports SMTP email functionality:

import 'package:mailer/smtp_server.dart';

bool success = await MailSender.sendEmail(
  from: 'sender@example.com',
  fromName: 'Sender Name',
  host: 'smtp.example.com',
  port: 587,
  to: ['recipient@example.com'],
  subject: 'Test Email',
  html: '<h1>Hello, World!</h1>',
  text: 'Hello, World!',
  username: 'smtp-username',
  password: 'smtp-password',
  ssl: true,
  allowInsecure: false,
);

MySQL Database Example

WebApp 2.0.1 includes powerful MySQL support:

import 'package:webapp/wa_mysql.dart';

// Create a query using the MySQL Query Builder
var query = Q()
  .selects([QSelectAll()])
  .from(QField('users'))
  .where(WhereOne(QField('status'), QO.EQ, QVar('active')))
  .orderBy(QOrder('created_at', desc: true))
  .limit(10);

// Generate SQL
String sql = query.toSQL();
// Output: SELECT * FROM `users` WHERE ( `status` = 'active' ) ORDER BY `created_at` DESC LIMIT 10

// Database migrations
var migration = MysqlMigration(mysqlConnection);
await migration.migrate(); // Run pending migrations
await migration.rollback(); // Rollback last migration

Running the Server

To start the server, run your main Dart file:

dart run

Or using the WebApp CLI:

webapp run

After the server starts, you'll see output like:

Example app started: http://localhost:8085

Next Steps