Hendry Lim
Hendry Lim

Reputation: 1974

Socket Not Listening with React Native and Express

BELOW MOBILE SIDE CODE CAN WORK ON IOS AND ANDROID HOWEVER GET WARNING 'Setting a time for long period of time, ie multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called......'.

By passing in the connectionConfig, i am able to get sockets working on both my android and ios simulator. However, i get a warning instead. Even though i commented out reconnection, reconnectionDelay and reconnectionAttempts, i still get those warnings. Anyone with experience on this and can share?

import React from "react";
import { Text, View, Button } from "react-native";
import SocketIO from "socket.io-client";

const connectionConfig = {
  // jsonp: false,
  // reconnection: true,
  // reconnectionDelay: 100,
  // reconnectionAttempts: 100000,
  transports: ["websocket"] // you need to explicitly tell it to use websockets
};

export default class HomeScreen extends React.Component {
  constructor() {
    super();
    this.socket = SocketIO("http://192.168.0.182:3000", connectionConfig);
    // this.socket = SocketIOClient("http://localhost:3000");
    this.socket.on("connect", () => {
      console.log("connected to server");
    });
    this.socket.emit("channel1", "Channel1 emitting");
  }

  btnPress = () => {
    console.log("Pressed");
    this.socket.emit("channel1", "Emitting when pressing button");
  };

  render() {
    return (
      <View>
        <Text>Hey</Text>
        <Button title="Emit" onPress={this.btnPress} />
      </View>
    );
  }
}

BELOW MOBILE SIDE CODE CANNOT WORK FOR ME

Im trying to implement a basic socket with react-native on frontend and express on backend.

My codes below doesn't seem to work. I emitted some communication from react-native but the server side doesn't seem to be listening as there is no console log.

Anyone can point out my error? Thanks

React-Native

import React from "react";
import { View, Text } from "react-native";
import SocketIOClient from "socket.io-client";

class HomeScreen extends React.Component {
  constructor(props) {
    super(props);

    this.socket = SocketIOClient("http://localhost:3000");

    this.socket.emit("channel1", "Hi Server");
  }

  render() {
    return (
      <View>
        <Text>Home</Text>
      </View>
    );
  }
}

export default HomeScreen;

Express and Node

    const express = require("express");
const path = require("path");
const http = require("http");
const socketIO = require("socket.io");

const publicPath = path.join(__dirname, "../public");
const port = process.env.PORT || 3000;

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

const { generateMessage } = require("./utils/message");

app.use(express.static(publicPath));

// Server listens to Client Connected
io.on("connection", socket => {
  console.log("New User Connected");

  //! Server emits to Client
  // socket.emit("newMessage", generateMessage('Admin', 'Welcome!!'));

  //! Server emits to Client
  socket.emit("welcome", generateMessage("Admin", "Welcome to the Chat App!!"));

  //! Server broadcast to Other Clients
  socket.broadcast.emit(
    "welcome",
    generateMessage("Admin", "New User Joined!!")
  );

  //! Server Listing to Client Event
  socket.on("createMessage", message => {
    console.log("createMessage", message);

    //! Emit to All Clients upon Server Listening
    io.emit("newMessage", generateMessage(message.from, message.text));

    //! Broadcast to All Clients (except emitter) upon Server Listening
    socket.broadcast.emit(
      "newMessage",
      generateMessage(message.from, message.text)
    );
  });

  socket.on("channel1", message => {
    console.log("channel1", message);
  });

  //! Listening to Client then Server Acknowledging
  socket.on("createMessageWithAcknowledgement", (message, callback) => {
    console.log("createMessageWithAcknowledgement", message);

    //! Emit to All Clients upon Server Listening
    io.emit("newMessage", generateMessage(message.from, message.text));
    callback({ admin: "Jack", role: "admin" });
  });

  //! Server listens to Client Disconnect
  socket.on("disconnect", () => {
    console.log("User Disconnected");
  });
});

server.listen(port, () => {
  console.log(`Server is up on port ${port}!`);
});

Upvotes: 0

Views: 1686

Answers (1)

Hendry Lim
Hendry Lim

Reputation: 1974

WORKING SOLUTION

REACT NATIVE

import React from "react";
import { Text, View, Button } from "react-native";
import SocketIO from "socket.io-client";

const connectionConfig = {
  // jsonp: false,
  // reconnection: true,
  // reconnectionDelay: 100,
  // reconnectionAttempts: 100000,
  transports: ["websocket"] // you need to explicitly tell it to use websockets
};

export default class HomeScreen extends React.Component {
  constructor() {
    super();
    this.socket = SocketIO("http://192.168.0.182:3000", connectionConfig);
    // this.socket = SocketIOClient("http://localhost:3000");
    this.socket.on("connect", () => {
      console.log("connected to server");
    });
    this.socket.emit("channel1", "Channel1 emitting");
  }

  btnPress = () => {
    console.log("Pressed");
    this.socket.emit("channel1", "Emitting when pressing button");
  };

  render() {
    return (
      <View>
        <Text>Hey</Text>
        <Button title="Emit" onPress={this.btnPress} />
      </View>
    );
  }
}

NODE & EXPRESS SERVER

const express = require("express");
const path = require("path");
const http = require("http");
const socketIO = require("socket.io");

const publicPath = path.join(__dirname, "../public");
const port = process.env.PORT || 3000;

const app = express();
const server = http.createServer(app);
const io = socketIO(server, {
      pingTimeout: 30000,
      pingInterval: 30000
    });

const { generateMessage } = require("./utils/message");

app.use(express.static(publicPath));

// Server listens to Client Connected
io.on("connection", socket => {
  console.log("New User Connected");

  //! Server emits to Client
  // socket.emit("newMessage", generateMessage('Admin', 'Welcome!!'));

  //! Server emits to Client
  socket.emit("welcome", generateMessage("Admin", "Welcome to the Chat App!!"));

  //! Server broadcast to Other Clients
  socket.broadcast.emit(
    "welcome",
    generateMessage("Admin", "New User Joined!!")
  );

  //! Server Listing to Client Event
  socket.on("createMessage", message => {
    console.log("createMessage", message);

    //! Emit to All Clients upon Server Listening
    io.emit("newMessage", generateMessage(message.from, message.text));

    //! Broadcast to All Clients (except emitter) upon Server Listening
    socket.broadcast.emit(
      "newMessage",
      generateMessage(message.from, message.text)
    );
  });

  socket.on("channel1", message => {
    console.log("channel1", message);
  });

  //! Listening to Client then Server Acknowledging
  socket.on("createMessageWithAcknowledgement", (message, callback) => {
    console.log("createMessageWithAcknowledgement", message);

    //! Emit to All Clients upon Server Listening
    io.emit("newMessage", generateMessage(message.from, message.text));
    callback({ admin: "Jack", role: "admin" });
  });

  //! Server listens to Client Disconnect
  socket.on("disconnect", () => {
    console.log("User Disconnected");
  });
});

server.listen(port, () => {
  console.log(`Server is up on port ${port}!`);
});

On a sidenote, adding below to your server side code will fix the timer warning. (I have already included below code amendment to my code solution above)

const io = socketIO(server, {
  pingTimeout: 30000,
  pingInterval: 30000
});

Upvotes: 1

Related Questions