【问题标题】:socket.io is not able to connect react-native and nodejssocket.io 无法连接 react-native 和 nodejs
【发布时间】:2020-07-24 03:37:19
【问题描述】:

我正在尝试在 nodejs 和 react-native 之间建立 websocket 连接。但不幸的是,它不起作用。

问题是客户端没有通过套接字与服务器连接。

这里是 nodejs(服务器端)代码

const express = require('express');
const app = express();

var server = app.listen(3000, () => console.log('server connected'))
const io = require("socket.io")(server)

io.on("connect", (socket) => {
  console.log("user connected");
  socket.on("chat message", mssg => {
    console.log(mssg);
    io.emit("chat message", mssg)
  })
})


app.get('/', (req, res) => {
  res.send("Hey! u are connected to server");
})

这里是 react-native(客户端)代码

import React from 'react'
import { Button } from 'react-native'
import io from 'socket.io-client'

export default class extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.socket = io("http://localhost:3000");
    this.socket.on('connect', () => console.log("connected"))
    this.socket.on("chat message", mssg => {
      console.log("mssg recieved in client:", mssg)
    })
  }
  render() {
    return <Button title="click to send message" onPress={() => {
      this.socket.emit("chat message", "anshika this side")
    }
    } />
  }
}

使用的库:react-native 版本:0.62.1,socket.io-client 版本:2.3.0(客户端),socket.io 版本:2.3.0(服务器端) )

【问题讨论】:

    标签: node.js react-native sockets


    【解决方案1】:

    我通过添加笔记本电脑的 ip 地址而不是将 localhost 作为 react-native 代码中的链接解决了这个问题

    【讨论】:

    • 我也遇到了这个错误,无论是 IP 还是 localhost。该应用程序正在使用 Expo,所以它的来源不同,这可能是问题吗?没有错误,套接字永远不会完全连接,并不断重试。
    【解决方案2】:

    你必须使用你的 ipv4 地址,关键是在 io 中将“transsports”参数指定为 ['websocket'] 在 web 应用程序中不需要的东西

    import io from 'socket.io-client'
    
    io('http://xxx.xxx.x.xxx:port', {
       transports: ['websocket']
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-30
      • 2020-02-12
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多