Reputation: 51
I followed a tutorial to create a easy React app /Node with Socket.IO. It worked perfectly, so I wanted to test it with other two devices:
The goal is to have the server running on my Desktop PC, using the browser to run the client and communicate from it to another client on the aforementioned devices.
Since I'm pretty new to this world, I'm not understanding what do I need to make it work. The Youtuber I followed through the tutorial posted the code which I forked here: https://github.com/machadop1407/socket-io-react-example and I made no changes at all.
public/src/index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
reportWebVitals();
public/src/app.js
import "./App.css";
import io from "socket.io-client";
import { useEffect, useState } from "react";
const socket = io.connect("http://localhost:3001");
function App() {
//Room State
const [room, setRoom] = useState("");
// Messages States
const [message, setMessage] = useState("");
const [messageReceived, setMessageReceived] = useState("");
const joinRoom = () => {
if (room !== "") {
socket.emit("join_room", room);
}
};
const sendMessage = () => {
socket.emit("send_message", { message, room });
};
useEffect(() => {
socket.on("receive_message", (data) => {
setMessageReceived(data.message);
});
}, [socket]);
return (
<div className="App">
<input
placeholder="Room Number..."
onChange={(event) => {
setRoom(event.target.value);
}}
/>
<button onClick={joinRoom}> Join Room</button>
<input
placeholder="Message..."
onChange={(event) => {
setMessage(event.target.value);
}}
/>
<button onClick={sendMessage}> Send Message</button>
<h1> Message:</h1>
{messageReceived}
</div>
);
}
export default App;
server/index.js
const express = require("express");
const app = express();
const http = require("http");
const { Server } = require("socket.io");
const cors = require("cors");
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log(`User Connected: ${socket.id}`);
socket.on("join_room", (data) => {
socket.join(data);
});
socket.on("send_message", (data) => {
socket.to(data.room).emit("receive_message", data);
});
});
server.listen(3001, () => {
console.log("SERVER IS RUNNING");
});
ngrok command: ngrok http 3000
Upvotes: 0
Views: 883
Reputation: 51
For a temporary make up solution:
But it's extremely important for you to remind closing the port you exposed on your router, plus, use a "not-so-important-pc" whom opens the port. It's just a quick way to see how it can work
Upvotes: 2