无法在Node.JS和React-Native(Socket.IO)之间建立连接

时间:2019-10-16 08:37:56

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

我是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);
});

实际上,部分代码可以正常工作,但是Socket.IO似乎死亡。 客户端没有得到任何响应,服务器也没有得到相同的响应,我认为Socket.IO服务器根本无法启动。

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

enter image description here

我什至在两台设备上都收到警告“无法识别的WebSocket连接选项'agent','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); });
    }

1 个答案:

答案 0 :(得分:2)

在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');
  });
});