简体   繁体   中英

Socket.io not connecting on React Native

I have a get started project using react native and socket.io My problem is that I am not able to get the socket connection.

I have pasted both of my codes below. Why do you think I am not able to connect? I looked over it and it looked fine to me.

My react native code is:

import React, { useState,useEffect,useCallback  } from 'react';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View,Button } from 'react-native';


import { io } from "socket.io-client";

var socket = null;
const ENDPOINT = "http://127.0.0.1:2222";
const options = {
  reconnection: false,
  timeout: 15000,
  autoConnect: true,
  forceNew : false
}
var socketsList = [];
export default function App() {

  useEffect(() => {
    console.log("here");
    socket = io("127.0.0.1:2222",options);
    socket.on("connect", () => {
      console.log("Connected"+socket.id);
  });
  socket.on("disconnect", () => {
      console.log("disconnected"); // undefined
  });
    console.log("here2");
  }, []);

  const onPressLearnMore = useCallback((e) => {
    
    e.preventDefault();
    if (socket==null) {
      console.log("null");
    }
    else {
      socket.connect();
      // console.log();
      console.log(socket.connected);
    }
    
  });

  return (
    <View style={styles.container}>
      <Button
        onPress={onPressLearnMore}
        title="Learn More"
        color="#841584"
        accessibilityLabel="Learn more about this purple button"
      />
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


  

And my node js server code is:

    var microtime = require('microtime');

const http = require('http');

const port = 2222, hostname = "localhost";

const httpServer = require("http").createServer().listen(port,hostname, () => {
  console.log(`Server running at ${hostname} :  ${port}`);
});

const socketOptions = {
  pingInterval: 10000,
  maxHttpBufferSize: 1e3,
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
}
const io = require("socket.io")(httpServer,socketOptions);

// var i = 0;

io.on("connection", (socket) => {
  console.log("CONNECTED "+socket.id);
  // console.log(i++);

  socket.on("disconnect", (reason) => {
    console.log("Disconnected "+socket.id);
  });

  socket.on("hello", (...args) => {
    console.log(args);
    let callback = args.length-1;
    callback("received");
  });

  socket.on('eventToEmit', function(data, callback){
    // console.log(data);
    console.log(microtime.now());
    callback('error', 'message',microtime.now() - data);
  });
});

Perhaps its about IP address. If you run it on emulator, 127.0.0.1 means your emulator and not your server. Based on your OS you can find your IP, for example for linux use ifconfig command.

Server.js

var app = require("express")();
var server = require("http").Server(app);
var io = require("socket.io")(server);
server.listen(5000);
io.on("connection", socket => {
console.log("socket id" + socket.id);
 });

App.js

import io from "socket.io-client/dist/socket.io.js";//<----import--
var e;
export default class App extends Component {
constructor(props) {
super(props);
e = this;
this.socket = io("http://PC IPAddress:5000", { jsonp: false });
}
}

Try to use this code,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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