[英]Socket.io on connection is not working on Flutter
Socket.io connection is not working on my flutter app. Socket.io 连接在我的颤振应用程序上不起作用。 I'm not getting any of the console logs printed in the io.on("connection"...) method of the index.js file.
我没有在 index.js 文件的 io.on("connection"...) 方法中打印任何控制台日志。 Why this is happening?
为什么会这样? (DB link is fine).
(数据库链接很好)。 On clicking the button Test Connection It's printing Line 18 but not invoking the socket emit.
单击按钮测试连接时,它正在打印第 18 行,但没有调用套接字发射。
My codes are as follows:我的代码如下:
socket_client.dart socket_client.dart
import 'package:socket_io_client/socket_io_client.dart' as IO;
class SocketClient {
IO.Socket? socket;
static SocketClient? _instance;
SocketClient._internal() {
socket = IO.io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
socket!.connect();
}
static SocketClient get instance {
_instance ??= SocketClient._internal();
return _instance!;
}
}
test_socket.dart test_socket.dart
import 'package:flutter/material.dart';
import 'package:socket_tutorial/utils/socket_client.dart';
class CreateRoomScreen extends StatefulWidget {
const CreateRoomScreen({Key? key}) : super(key: key);
@override
State<CreateRoomScreen> createState() => _CreateRoomScreenState();
}
class _CreateRoomScreenState extends State<CreateRoomScreen> {
final _socketClient = SocketClient.instance.socket!;
test() {
print('Line 18');
_socketClient.emit("test", "Socket Connected");
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
margin: const EdgeInsets.symmetric(
horizontal: 20,
),
child: ElevatedButton(
onPressed: test,
child: const Text(
"Test Connection",
style: TextStyle(
fontSize: 16,
color: Colors.white,
),
),
)),
),
);
}
}
index.js index.js
// IMPORTS
const express = require("express");
const http = require("http");
const mongoose = require("mongoose");
// create a server
const app = express();
const port = process.env.PORT || 3000;
var server = http.createServer(app);
var io = require("socket.io")(server);
// middle ware
app.use(express.json());
// connect to mongodb
const DB = "link";
// listening to socket io events from the client (flutter code)
io.on("connection", (socket) => {
console.log(socket.id);
socket.on("test", (data) => {
console.log(data);
})
});
mongoose
.connect(DB)
.then(() => {
console.log("Connection Successful!");
})
.catch((e) => {
console.log(e);
});
// listen to server
server.listen(port, "0.0.0.0", () => {
console.log(`Server started and running on port ${port}`);
});
Try calling the test()
in initState尝试在 initState 中调用
test()
@override
void initState() {
super.initState();
test();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.