【问题标题】:Unable to establish connection between Node.JS and React-Native (Socket.IO)无法在 Node.JS 和 React-Native (Socket.IO) 之间建立连接
【发布时间】:2020-02-12 23:40:59
【问题描述】:

我是 ReactNode 的新手,我正在尝试使用 Socket.IO 制作一个简单的 WebSocket,它会简单地向所有连接的用户和用户发送问候将响应服务器。

Node.JS 服务器在 Windows PC 上运行,而 React-Native 应用在 iOS 和 Android 设备上运行。

Node.JS服务器代码如下

var app = require('express')();
var http = require('http').createServer(app);
var io   = require('socket.io')(http);
const bodyParser = require('body-parser');
const mysql = require('mysql');


const connection = mysql.createPool({
  host     : 'localhost',
  user     : 'root',
  password : 'block',
  database : 'visualpos'
});

// Creating a GET route that returns data from the 'users' table.
app.get('/prenotazioni', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

    // Executing the MySQL query (select all data from the 'users' table).
    connection.query("SELECT Data, Importo_Doc FROM tabella_pagamenti", function (error, results, fields) {
      // If some error occurs, we throw an error.
      if (error) throw error;

      // Getting the 'response' from the database and sending it to our route. This is were the data is.
      res.send(results)
    });
    connection.release();
  });
});

app.get('/', function(req, res){
  res.send('<h1>Hello World</h1>');
});

// Starting our server.
http.listen(3000, () => {
 console.log('In ascolto sulla porta *:3000');
});

io.emit('saluta', 'Ciao dal server :)');
io.on('connected', (data) => {
   console.log(data);
});

实际上 GET 部分代码运行良好,但 Socket.IO 似乎死亡。 客户端没有得到任何响应和服务器相同,我认为 Socket.IO 服务器根本没有启动..

在 XCode Debug 中,当应用程序在 iPhone 上运行时出现以下错误

我什至在两台设备上都收到警告“无法识别的 WebSocket 连接选项‘代理’、‘perMessageDeflate’、...”

这是我在 React-Native 中使用的代码

import io from 'socket.io-client'

    var socket = io('http://192.168.100.50:3000', {
        jsonp: false,
        transports: ['websocket'],
        autoConnect: true,
        reconnection: true,
        reconnectionDelay: 500,
        reconnectionAttempts: Infinity
    });

    componentDidMount(){
     socket.emit('connected','we');
     socket.on('saluta',(data) => { alert(data); });
    }

【问题讨论】:

标签: ios node.js reactjs react-native socket.io


【解决方案1】:

在 socket.io getStarted 部分,他们使用“连接”事件而不是“已连接”事件 (https://socket.io/get-started/chat/)。

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 2021-05-29
    • 2021-09-02
    • 2020-12-28
    • 2019-03-31
    • 2014-04-10
    • 1970-01-01
    相关资源
    最近更新 更多