簡體   English   中英

Flutter socket.io 客戶端未通過 https 與 node.js socket.io 服務器連接

[英]Flutter socket.io client not connecting with node.js socket.io server via https

我正在嘗試通過 https 將 flutter socket.io 客戶端連接到 node.js socket.io 客戶端,但這並沒有發生。 通過瀏覽器,我能夠建立連接並在移動設備中使用 http,但由於某種原因切換到 https 不起作用。

以下是我的 node.js 服務器端代碼。

var fs = require('fs');
var https = require('https');

var express = require('express');
var app = express();

var options = {
  key: fs.readFileSync('./file.pem'),
  cert: fs.readFileSync('./file.crt')
};
var serverPort = 3000;

var server = https.createServer(options, app);
var io = require('socket.io')(server);

app.get('/', function(req, res) {
  res.send("Node Server is running. Yay!!")
});

io.on('connection', function(socket) {
  console.log('new connection');
  socket.emit('message', 'This is a message from the dark side.');
});

server.listen(serverPort, function() {
  console.log('server up and running at %s port', serverPort);
});

這是代碼的顫動方面。

import 'package:flutter/material.dart';
import 'package:socket_io_client/socket_io_client.dart';

class TestSocket extends StatefulWidget {
  const TestSocket({Key? key}) : super(key: key);

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

class _TestSocketState extends State<TestSocket> {
  late Socket socket;
  @override
  void initState() {
    super.initState();
    socketServer();
  }

  // Socket Connection
  void socketServer() {
      try {
            // Configure socket transports
      socket = io('https://<localhost>:3000', <String, dynamic>{
        'transpose': ['websocket'],
        'autoConnect': false
      });

      // Connect to websocket
      socket.connect();

      // Handle socket events
      socket.on('connection', (_) => print("Connected with ${socket.id}"));

    } catch (e) {
      print('The error is ${e.toString}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

我正在將 socket.io 版本“^2.4.1”與 node.js 和 socket_io_client: ^1.0.1 與顫動一起使用。

嘗試將其添加到 main.dart 文件中,請不要使用“localhost”-> 1.1.1.1:3000 更好

https://github.com/SelimhanBek/flutter-socket-io-demo這個在 https 和 http 端工作的示例,希望有用...

// Security Policy ...
class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
  }
}

void main() {
  HttpOverrides.global = MyHttpOverrides();
  runApp(MyApp());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM