LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Overview
  • 1. Installing WebSocket Server (Optional)
  • 2. Create a WebSocket Service in Aurelia
  • 3. Register the Service in main.ts
  • 4. Implement WebSockets in a Component
  • 5. Add the Chat Component to the App
  • Key Features
  • Next Steps

Was this helpful?

Export as PDF
  1. Developer Guides
  2. Recipes

WebSockets Integration

Overview

WebSockets enable real-time bidirectional communication between clients and servers. Unlike HTTP polling, WebSockets keep a persistent connection open, allowing instant updates. This guide walks through integrating WebSockets into an Aurelia 2 application.


1. Installing WebSocket Server (Optional)

If you do not already have a WebSocket server, you can set up a simple Node.js WebSocket server.

npm install ws

Create server.js:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('Client connected');

  ws.on('message', (message) => {
    console.log('Received:', message);
    ws.send(`Server response: ${message}`);
  });

  ws.on('close', () => console.log('Client disconnected'));
});

console.log('WebSocket server running on ws://localhost:8080');

Run it with:

node server.js

2. Create a WebSocket Service in Aurelia

Create a WebSocket service to manage connections.

// src/services/websocket-service.ts
export class WebSocketService {
  private socket: WebSocket;

  constructor(private url: string) {
    this.socket = new WebSocket(url);
  }

  connect(onMessage: (data: string) => void) {
    this.socket.onmessage = (event) => onMessage(event.data);
    this.socket.onopen = () => console.log('WebSocket connected');
    this.socket.onclose = () => console.log('WebSocket closed');
    this.socket.onerror = (err) => console.error('WebSocket error:', err);
  }

  sendMessage(message: string) {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    } else {
      console.warn('WebSocket is not open');
    }
  }
}

3. Register the Service in main.ts

import Aurelia from 'aurelia';
import { WebSocketService } from './services/websocket-service';
import { MyApp } from './my-app';

Aurelia
  .register(WebSocketService)
  .app(MyApp)
  .start();

4. Implement WebSockets in a Component

Create a simple real-time chat interface.

// src/components/chat.ts
import { customElement } from 'aurelia';
import { WebSocketService } from '../services/websocket-service';

@customElement({
  name: 'chat',
  template: `
    <input type="text" value.bind="message" placeholder="Type a message..." />
    <button click.trigger="sendMessage()">Send</button>
    <ul>
      <li repeat.for="msg of messages">${msg}</li>
    </ul>
  `
})
export class Chat {
  message = '';
  messages: string[] = [];
  private webSocketService = new WebSocketService('ws://localhost:8080');

  constructor() {
    this.webSocketService.connect((data) => {
      this.messages.push(`Server: ${data}`);
    });
  }

  sendMessage() {
    if (this.message.trim()) {
      this.messages.push(`You: ${this.message}`);
      this.webSocketService.sendMessage(this.message);
      this.message = '';
    }
  }
}

5. Add the Chat Component to the App

<!-- src/my-app.html -->
<template>
  <h1>Real-Time Chat</h1>
  <chat></chat>
</template>

Key Features

  • Persistent WebSocket connection for real-time updates.

  • No polling required, reducing unnecessary HTTP requests.

  • Works with any WebSocket server, including GraphQL subscriptions and Firebase real-time database.

  • Easily extendable for authentication, user presence, and additional real-time interactions.


Next Steps

  • Implement server-side authentication for secure WebSocket connections.

  • Use GraphQL subscriptions instead of raw WebSockets.

  • Add presence indicators (e.g., "User is typing...").

  • Extend functionality to support binary data transfer (images, files, etc.).

PreviousTailwindCSS integrationNextWeb Workers Integration

Last updated 2 months ago

Was this helpful?