簡體   English   中英

Socket.io 連接在 Flutter 和 Nodejs 中不起作用

[英]Socket.io connection not working in Flutter and Nodejs

請我在 Flutter 中使用 socket_io_client 包來處理 Nodejs 中的 socket io。 socket.io 在服務器 (Nodejs) 上運行良好,但在客戶端 (Flutter) 上它無法連接到服務器。 這是我的代碼如下:

服務器代碼

const express = require( 'express' ),
    app = express(),
    httpServer = require( 'http' ).createServer( app ),
    io = require( 'socket.io' )( httpServer );
httpServer.listen( 3000, () => console.log( 'Server is running' ) );
let connectedUsers = [];
io.on( 'connection', ( socket ) =>
{
    console.log(socket.id);
    connectedUsers.push( {
        socketId: socket.id,
    } );

    socket.on( 'connectedUsers', ( _ ) =>
    {
        socket.broadcast.emit( 'connectedUsers', connectedUsers );
    } );

    socket.on( "connectedUser", ( data ) =>
    {
        console.log( data );
        const { userId, userName } = data;
    });

    socket.on( 'disconnect', () =>
    {
        const disConnectedUsers = connectedUsers.filter(
            ( user ) => user.socketId !== socket.id
        );
        const leavingUser = connectedUsers.find(
            ( user ) => user.socketId === socket.id
        );
        connectedUsers = disConnectedUsers;
        console.log( connectedUsers );
        connectedUsers.forEach( ( user ) =>
            io.to( user.socketId ).emit( 'leavingUser', leavingUser )
        );
    } );
} );

客戶端代碼

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:line_icons/line_icons.dart';
import 'package:sharpcall/providers/theme_notifier.dart';
import 'package:sharpcall/views/components/destination_item.dart';
import 'package:sharpcall/views/screens/contact_screen.dart';
import 'package:sharpcall/views/screens/phone_screen.dart';
import 'package:sharpcall/views/screens/favorite_screen.dart';
import 'package:sharpcall/views/screens/setting_screen.dart';
import 'package:socket_io_client/socket_io_client.dart' as client;

final _stateBottomIndex = StateProvider<int>((ref) => 0);

class MainScreen extends StatefulWidget {
  final StateNotifierProvider<ThemeNotifier, bool> themeNotifier;

  const MainScreen({
    Key? key,
    required this.themeNotifier,
  }) : super(key: key);

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  final PageController _pageController =
      PageController(initialPage: 0, keepPage: true);

  @override
  void initState() {
    client.Socket socket = client.io('http://192.168.42.51:3000');
    socket.onConnect((data) => socket.emit("connectedUser", {
          "userId": socket.id,
          "userName": "Woo Bear",
        }));

    socket.on("connectedUsers", (data) => print(data));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context, watch, child) {
        final stateBottomIndex = watch(_stateBottomIndex);
        return Scaffold(
          body: SizedBox(
            child: PageView(
              allowImplicitScrolling: true,
              physics: const BouncingScrollPhysics(),
              controller: _pageController,
              onPageChanged: (value) {
                stateBottomIndex.state = value;
              },
              children: [
                const PhoneScreen(),
                const ContactScreen(),
                const FavoriteScreen(),
                SettingScreen(
                  themeNotifier: widget.themeNotifier,
                ),
              ],
            ),
          ),
          bottomNavigationBar: NavigationBarTheme(
            data: NavigationBarThemeData(
              backgroundColor: Theme.of(context).scaffoldBackgroundColor,
              height: kBottomNavigationBarHeight,
              indicatorColor: Colors.transparent,
            ),
            child: NavigationBar(
              selectedIndex: stateBottomIndex.state,
              onDestinationSelected: (value) {
                _pageController.animateToPage(
                  value,
                  duration: const Duration(milliseconds: 200),
                  curve: Curves.easeInOut,
                );
                stateBottomIndex.state = value;
              },
              backgroundColor: Theme.of(context).scaffoldBackgroundColor,
              animationDuration: const Duration(milliseconds: 300),
              destinations: [
                DestinationItem(
                  stateBottomIndex: stateBottomIndex.state,
                  icon: LineIcons.phone,
                  name: "Phone",
                  initialIndex: 0,
                ),
                DestinationItem(
                  stateBottomIndex: stateBottomIndex.state,
                  icon: Icons.perm_contact_calendar_outlined,
                  name: "Contacts",
                  initialIndex: 1,
                ),
                DestinationItem(
                  stateBottomIndex: stateBottomIndex.state,
                  icon: LineIcons.star,
                  name: "Favorites",
                  initialIndex: 2,
                ),
                DestinationItem(
                  stateBottomIndex: stateBottomIndex.state,
                  icon: LineIcons.cogs,
                  name: "Settings",
                  initialIndex: 3,
                ),
              ],
            ),
          ),
          floatingActionButton: stateBottomIndex.state == 2
              ? FloatingActionButton(
                  backgroundColor: Theme.of(context).canvasColor,
                  onPressed: () {},
                  child: Icon(
                    Icons.star_border,
                    color: Theme.of(context).textTheme.headline1!.color,
                  ),
                )
              : null,
        );
      },
    );
  }
}

我正在使用我的遠程 IP 地址在我的真實 Android 設備上測試該應用程序。 請問我錯過了什么或需要在服務器上進行配置嗎? 請幫幫我。

如果您在本地服務器上運行,則需要一個反向代理來連接到您的服務器。 如果您的 android 設備是通過 USB 連接的,請嘗試在您的終端中運行adb reverse tcp:3000 tcp:3000 ,您將能夠連接到您的本地 nodejs 服務器

暫無
暫無

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

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