socket.io:Heroku:颤振:Heroku 发射()不工作

时间:2021-01-24 08:39:29

标签: node.js flutter heroku socket.io

编辑/注意:我什至尝试过 Heroku 的示例并部署它。 事件没有发出。 https://devcenter.heroku.com/articles/node-websockets#option-2-socket-io

我在 heroku 上部署了服务器。这使用socket.io。我有一个 Flutter 应用程序作为客户。套接字连接正在工作。服务器正在打印客户端 ID 等。但 emit() 不起作用。这是我所拥有的。

  1. 我在 Heroku 上启用了 http 关联:$ heroku features:enable http-session-affinity -a my-heroku-app

  2. index.js

index.js 就是这么简单。在其他一些 Stackoverflow 帖子中,我读到将 io.emit() 更改为 server.emit() 应该可以工作。我试过了,但没有运气。

const server = require('http').createServer()
const io = require('socket.io')(server)

console.log("Starting application...");

io.on('connection', function (client) {

  console.log('client connect...', client.id);

  client.on('typing', function name(data) {
    console.log("Received typing event from ", client.id);
    console.log(data);
    io.emit('typing', data)
  })

  client.on('message', function name(data) {
    console.log("Received message event from ", client.id);
    console.log(data);
    io.emit('message', data)
  })

  client.on('connect', function () {
  })

  client.on('disconnect', function () {
    console.log('client disconnect...', client.id)
    // handleDisconnect()
  })

  client.on('error', function (err) {
    console.log('received error from client:', client.id)
    console.log(err)
  })
})

var server_port = process.env.PORT || 3000;
server.listen(server_port, function (err) {
  if (err) throw err
  console.log('server is listening on port %d', server_port);
});
  1. 对于客户:main.dart 是这样的: 简而言之,我在这里所做的是......当我收到 'message' 事件时,我调用 handleMessage 方法,该方法只打印收到的数据。但没有打印出来。
import 'package:flutter/material.dart';
import 'package:socket_io_client/socket_io_client.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String receivedMessage = "";
  Socket socket;

  @override
  void initState() {
    super.initState();
    connectToServer();
  }

  void _incrementCounter() {
    print("Sending message from client device");
    setState(() {
      _counter++;
      sendMessage(_counter.toString());
      sendTyping(true);
    });
  }

  void connectToServer() {
    try {
      // Configure socket transports must be sepecified

      socket = io('https://my-heroku-app.herokuapp.com/', <String, dynamic>{
        'transports': ['websocket'],
        'autoConnect': false,
      });

      // Connect to websocket f
      socket.connect();

      // Handle socket events
      socket.on('connect', (_) => print('connect: ${socket.id}'));
      socket.on('location', handleLocationListen);
      socket.on('typing', handleTyping);
      socket.on('message', handleMessage);
      socket.on('disconnect', (_) => print('disconnect'));
      socket.on('fromServer', (_) => print(_));
    } catch (e) {
      print(e.toString());
    }
  }

  // Send a Message to the server
  sendMessage(String message) {
    print("Sending message from client: ");
    socket.emit(
      "message",
      {
        "id": socket.id,
        "message": message, // Message to be sent
        "timestamp": DateTime.now().millisecondsSinceEpoch,
      },
    );
  }

  // Listen to all message events from connected users
  void handleMessage(Map<String, dynamic> data) {
    print("Received message from a client");
    print(data);
    setState(() {
      receivedMessage = '$data';
    });
  }

  // Send Location to Server
  sendLocation(Map<String, dynamic> data) {
    socket.emit("location", data);
  }

  // Listen to Location updates of connected usersfrom server
  handleLocationListen(Map<String, dynamic> data) async {
    print(data);
  }

  // Send update of user's typing status
  sendTyping(bool typing) {
    socket.emit("typing", {
      "id": socket.id,
      "typing": typing,
    });
  }

  // Listen to update of typing status from connected users
  void handleTyping(Map<String, dynamic> data) {
    print('Typing received');
    print(data);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            Text(
              'Message received: $receivedMessage',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

0 个答案:

没有答案