Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

node.js - socket.io: Heroku: Flutter: Heroku emit() is not working

Edit/Note: I even have tried Heroku's example and deployed it. The events are not emitting. https://devcenter.heroku.com/articles/node-websockets#option-2-socket-io

I deployed server on heroku. This uses socket.io. And I have a flutter app as clients. The socket connect is working. Server is printing client id etc. But emit() is not working. Here is what I have on it.

  1. I have enabled http affinity on Heroku: $ heroku features:enable http-session-affinity -a my-heroku-app

  2. index.js

index.js is as simple as this. In some other Stackoverflow post I read that changing io.emit() to server.emit() should work. I tried it but no luck.

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. For client: main.dart is this: What I am doing here is, in short, is... when I receive 'message' event, I call handleMessage method, which just prints the data received. But nothing gets printed.
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.
    );
  }
}
question from:https://stackoverflow.com/questions/65868572/socket-io-heroku-flutter-heroku-emit-is-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...