I have tried to use socket.io with flutter. But I get the following error.
D/FlutterSocketIoPlugin: SocketIO( 6279): reconnect_attempt: [108]
D/FlutterSocketIoPlugin: SocketIO( 6279): reconnecting: [108]
D/FlutterSocketIoPlugin: SocketIO( 6279): connect_error: [{"cause":{"detailMessage":"CLEARTEXT communication to 10.0.2.2 not permitted by network security policy","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"websocket error","stackTrace":[],"suppressedExceptions":[]}]
I wrote the server using nodejs.
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const { Socket } = require('dgram');
const formatMessage = require('./utils/messages');
const {userJoin, getCurrentUser, userLeave, getRoomUsers} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const botName = 'ChatCordBot';
//run when client connects
io.on('connection', socket=>{
socket.on('joinroom',({username, room})=>{
const user = userJoin(socket.id, username, room);
socket.join(user.room);
socket.emit('message',formatMessage(botName,'Welcome to chatcord!'));
//broadcast
socket.broadcast.to(user.room).emit('message',formatMessage(botName,`${user.username} has joined`));
//send users and room info
io.to(user.room).emit('roomusers',{
room:user.room,
users:getRoomUsers(user.room)
});
});
// Listen for chatMessage
socket.on('chatMessage', msg => {
// const user = getCurrentUser(socket.id);
// io.to(user.room).emit('message', formatMessage(user.username, msg));
console.log(msg);
});
//runs when client disconnects
socket.on('disconnect',()=>{
const user = userLeave(socket.id);
if(user){
io.to(user.room).emit('message',formatMessage(botName,`${user.username} has left the chat`));
//send users and room info
io.to(user.room).emit('roomusers',{
room:user.room,
users:getRoomUsers(user.room)
});
}
});
});
const PORT = 3000;
server.listen(PORT,()=>{console.log(`Listening to ${PORT}`)});
Here is part of the client side where I used socket.io.
import 'package:flutter_socket_io/flutter_socket_io.dart';
import 'package:flutter_socket_io/socket_io_manager.dart';
class Body extends StatefulWidget {
const Body({
Key key,
}) : super(key: key);
@override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
SocketIO socketIO;
@override
// ignore: must_call_super
void initState(){
initSocketIO();
}
initSocketIO(){
socketIO = SocketIOManager().createSocketIO('http://10.0.2.2:3000', '/');
socketIO.init();
socketIO.subscribe('chatMessage', getMessage);
socketIO.connect();
}
getMessage(){
if(socketIO != null){
print("socket is not null");
}
}
I'm running my flutter app using the android emulator in android stuudio. Is that the cause for the error?
Or is there some error in my code?
question from:
https://stackoverflow.com/questions/65942553/flutter-with-socket-io 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…