NodeJS 使用Socket.io无法在React Native移动的应用中工作

csga3l58  于 2023-04-20  发布在  Node.js
关注(0)|答案(3)|浏览(148)

我已经尝试连接套接字与React Native移动的应用程序.节点服务器socket.io是工作,我有与react web使用,但当我使用React Native移动应用程序有不工作
客户端(React Native

import io from 'socket.io-client';

const ENDPOINT = "http://192.168.1.3:7000";
const socket = io(ENDPOINT, {transports: ['websocket']});

const getMessage = () => {
  socket.on('getMessage', (data) => {
    console.log('socket data', data);
  })
};

const sendMessage = () => {
  var userid = log.userid
  var message = "msg from app"
  socket.emit('send msg', { userid, message });
}

服务器(节点J)

const app = express();
const server = app.listen(7000);
const io = require('socket.io')(server, {
cors : {
    origin:'*'
  }
});

io.on("connection",(socket)=>{
  socket.on('sendMessage',({userid, message})=>{
    io.emit('getMessage',{userid, message});
  })
})
km0tfn4u

km0tfn4u1#

dev!我解决了这个问题,只是没有使用socket.io。我发现Socket.io在移动的应用程序中不是一个好的选择。使用WebSocket API代替。
React组分

import React from 'react';
import { View, Text } from 'react-native';

class WebSocketConnection extends React.Component {

    constructor(props) {
        super(props);
        this.webSocket = this.webSocket.bind(this);
    }

    webSocket() {
        const ws = new WebSocket('ws:172.16.20.201:8080');

        ws.onopen = (e) => {
            console.log('connected on wsServer');
        }
        
        ws.addEventListener('open', function (event) {
            ws.send('Hello from React Native!');
        });
        
        ws.addEventListener('message', function (event) {
            this.message = event.data;
            console.log('Message from server ', event.data);
        });
        
        ws.onerror = (e) => {
            console.log(e);
        }
    }
    
    render() {
        return (
            <View>
                <Text>
                    Socket.io YES
                </Text>
            </View>
        )
    }

    componentDidMount() {
        this.webSocket();
    }

}

export default WebSocketConnection;

服务器

/**
 * Create WebSocket server.
 */

const WebSocket = require('ws');
const serverWs = new WebSocket.Server({
  port: 8080
});

let sockets = [];
serverWs.on('connection', function(socket) {
  sockets.push(socket);

  console.log(`connectet client`);

  // When you receive a message, send that message to every socket.
  socket.on('message', function(msg) {
    console.log(msg);
    sockets.forEach(s => s.send(msg));
  });

  // When a socket closes, or disconnects, remove it from the array.
  socket.on('close', function() {
    sockets = sockets.filter(s => s !== socket);
  });
});

在使用Express时,我将此服务器绑定在/bin/www中,并正常工作。

jslywgbw

jslywgbw2#

当我将react-native更改为使用ws协议时,我能够工作。

useEffect(()=>{
        const socket = io("ws://localhost:3000");
        socket.on("connect", () => {
            console.log(socket.connected); // true
        });
    },[])
pod7payv

pod7payv3#

你的代码应该可以工作。
只是想把emit中的主题改成“sendMessage”

const sendMessage = () => {
        var userid = log.userid
        var message = "msg from app"
        socket.emit('sendMessage', { userid, message });
    }

添加错误登录后,刚刚创建套接字一样,如below

io.on("connect_error", (err) => {
     console.log(`connect_error due to ${err.message}`);
    });

找到错误可能会有帮助

相关问题