Dart Server supports Web Sockets

[EDIT: Updated on 2013-12-05]

Dart is a structured web programming language that runs on the client and the server. Web sockets are bi-directional data channels for real-time streaming communication between modern web browsers and servers. Thanks to a recent commit, Dart Servers can host Web Socket connections now!

You'll need a copy of the Dart SDK as of 2013-03-05 for this to work.

Dart already ships with basic HttpServer functionality. The new Web Socket is built on top of HttpServer, so it slides right into an existing Dart server app.

The following code snippet is a simple example of a Web Socket echo server running in Dart.

import 'dart:io';

void main() {

  HttpServer.bind('127.0.0.1', port)
    .then((HttpServer server) {
      print('listening for connections on $port');

      server.listen((HttpRequest request) {
        if (request.uri.path == '/ws') {
          WebSocketTransformer.upgrade(request).then((WebSocket websocket) {
            websocket.listen((message) => handleMessage(message));
            // or: websocket.listen(handleMessage);
          });
        } else {
          /* ... */
        }
      });
    },
    onError: (error) => print("Error starting HTTP server: $error"));
}
Once you have this running, you can use a simple Web Socket test page to connect and receiving echo messages. For example, if you are running the above code, you can connect to ws://localhost:8000/ws

As always, the Dart team wants to hear your feedback. Please don't hesitate to join the Dart mailing list and file bugs and feature requests at dartbug.com. Thanks!

Popular posts from this blog

Lists and arrays in Dart

The 29 Healthiest Foods on the Planet

Converting Array to List in Scala