I am trying to connect flutter socket.io client to node.js socket.io client via https, but that is not happening. Via browser I am able to establish connection and also using http in mobile, but for some reason switching to https is not working.
The following is my node.js server side code.
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);
});
And this is flutter side of code.
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();
}
}
I am using socket.io version "^2.4.1" with node.js and socket_io_client: ^1.0.1 with flutter.
Try add this to main.dart file and please do not use the "localhost" -> 1.1.1.1:3000 is better
https://github.com/SelimhanBek/flutter-socket-io-demo this sample which is worked on https and http side, hope that useful ...
// 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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.