快速构建WebSocket服务端

2139次阅读  |  发布于5年以前

快速构建WebSocket服务端

Upgrade a regular HTTP request to a WebSocket request using WebSocketTransformer.upgrade().

import 'dart:io';

handleMsg(msg) {
  print('Message received: $msg');
}

main() async {
  try {
    var server = await HttpServer.bind('127.0.0.1', 4040);
    await for (HttpRequest req in server) {
      if (req.uri.path == '/ws') {
        // Upgrade an HttpRequest to a WebSocket connection.
        var socket = await WebSocketTransformer.upgrade(req);
        socket.listen(handleMsg);
      }
    }
  } catch (e) {
    print(e);
  }
}

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8