Flutter 的 web_socket_channel 悄无声息地失败了

Flutter's web_socket_channel fails silently

正在尝试关注 https://flutter.dev/docs/cookbook/networking/web-sockets

一个极简的 flutter 程序,试图向我的服务器发送消息:

import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.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,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {

  void sendMessage(String message){

    final channel = WebSocketChannel.connect(
      Uri.parse('ws://192.1XX.XX.XX:5000'),);
    channel.sink.add(message);
    return;}


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('Dor'),
            TextButton(onPressed: (){
              sendMessage('Message text should go here');
            }, child: Text('PressMe'))
          ],
        ),
      ),

    );
  }
}

但是,这不会向我的服务器发送任何内容。没有错误消息,因此调试具有挑战性... 服务器正在运行,因为以下客户端代码确实将数据发送到我的服务器:

<html>
<head>
<title>Chat Room</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.2/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {

    var socket = io.connect('ws://192.XXX.XX.XX:5000');

    socket.on('connect', function() {
        socket.send('User has connected!');
    });

    socket.on('message', function(msg) {
        $("#messages").append('<li>'+msg+'</li>');
        console.log('Received message');
    });

    $('#sendbutton').on('click', function() {
        socket.send($('#myMessage').val());
        $('#myMessage').val('');
    });

});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>

但为了以防万一你需要它,这是我服务器的代码:

from flask import Flask
from flask_socketio import SocketIO, send

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'
socketio = SocketIO(app, cors_allowed_origins='*')

@app.route('/hello')
def say_hello():
    return 'HTTP is working!'


@socketio.on('message')
def handleMessage(msg):
    print('Message: ' + msg)
    send(msg, broadcast=True)

if __name__ == '__main__':
    socketio.run(app,host='0.0.0.0',port=5000)

您的服务器实现了 Socket.IO 协议,这与 WebSocket 不同。如果您的 flutter 应用程序打算连接到 Socket.IO 服务器,则应使用 Socket.IO 客户端。