簡體   English   中英

socket.io 無法連接 react-native 和 nodejs

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

我正在嘗試在nodejs和react-native之間建立websocket連接。 但不幸的是,它不起作用。

問題是客戶端沒有通過 sockets 與服務器連接。

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

這是本機(客戶端)代碼

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(服務器端)

我通過添加筆記本電腦的 ip 地址而不是將localhost作為 react-native 代碼中的鏈接解決了這個問題

您必須使用您的 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