简体   繁体   English

socket.io 无法连接 react-native 和 nodejs

[英]socket.io is not able to connect react-native and nodejs

I am trying to establish websocket connection between nodejs and react-native.我正在尝试在nodejs和react-native之间建立websocket连接。 But unfortunately it is not working.但不幸的是,它不起作用。

The issue is that client side do not get connected with server via sockets.问题是客户端没有通过 sockets 与服务器连接。

Here is nodejs (server-side) code这是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");
})

Here is react-native(client-side) code这是本机(客户端)代码

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")
    }
    } />
  }
}

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

I solved the issue by adding ip address of my laptop instead of putting localhost as a link in react-native code我通过添加笔记本电脑的 ip 地址而不是将localhost作为 react-native 代码中的链接解决了这个问题

you must use your ipv4 address and the catch was to specify "transports" parameters in io as ['websocket'] what's no needed in web apps您必须使用您的 ipv4 地址,并且要注意的是在 io 中将“传输”参数指定为 ['websocket'] 在 web 应用程序中不需要什么

import io from 'socket.io-client'

io('http://xxx.xxx.x.xxx:port', {
   transports: ['websocket']
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM