I am trying to socket.io to react native. It works perfectly fine on iOS device but doesn't work on android. I was doing some research and found out you need to usesCleartextTraffic="true".
I did that and its still not working. Below is my code. Any help would be really appreciated.
server code
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer)
io.on("connection", (socket) => {
socket.on("hello",function (){
io.emit("hello", "worldd");
})
});
httpServer.listen(3000);
Client Side
useEffect(()=> {
try {
const socket = io('http://localhost:3000');
socket.on("hello", (param) => {
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
console.log(param);
});
} catch (e) {
console.log(e)
}
});
CodePudding user response:
I think first you need to change the way you are setting up you server, change it to this instead as suggested by the documentation
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = new Server(server);
The calling socket emit and on seems to be correct so try this and let me know if it works. you can also check full documentation here https://socket.io/get-started/chat
CodePudding user response:
As @Mustafa mentioned, createServer method comes from http module. So:
Server side:
const { Server } = require("socket.io");
const http = require('http'); const server = http.createServer(app);
const io = new Server();
io.on("connection", (socket) => {
socket.on("hello", (param) => {
io.sockets.emit("hello", param);
});
});
io.attach(server); // Attach socket.io to the server
server.listen(3000);
Client side:
- Listen to "connect" event to make sure that the connection was successful.
- Emit "hello" event for the server to respond back to this event.
So:
import { io } from "socket.io-client";
const socket = io('http://localhost:3000');
socket.on("hello", (param) => {
console.log(param);
});
socket.on("connect", () => {
console.log("Successfully connected!");
socket.emit("hello", "world");
});