Reputation: 6491
I'm trying to implement websockets. It manages to make a connection and prints Backend, connected!
and Frontend, connected!
, but when I type text into the input and press send, it just prints Frontend, connected!
a bunch more times and nothing happens. What am I doing wrong here?
Here's what I have:
// server.js
const express = require("express");
const app = express();
app.use("/api/messages", require("./routes/api/messages"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
// routes/api/messages.js
const express = require("express");
const router = express.Router();
const server = require("http").createServer();
const io = require("socket.io")(server, {
path: "/socket",
serveClient: false,
pingInterval: 10000,
pingTimeout: 5000,
cookie: false
});
io.on("connection", () => {
console.log("Backend, connected!");
});
io.on("msg", function(msg) {
console.log("entered!"); // <--- never prints!
console.log("message: " + msg);
});
server.listen(5001);
router.post(...)
router.get(...)
module.exports = router;
And on my React Native front end, in one of my screens in React Navigation:
const Conversation = ({
navigation,
auth: { user },
sendMessage
}) => {
const [replyText, setReplyText] = useState("");
const socket = io("http://192.168.112.110:5001", {
path: "/socket",
transports: ["websocket"],
jsonp: false
});
useEffect(() => {
socket.connect();
socket.on("connect", () => {
console.log("Frontend, connected!");
});
socket.on("works?", () => {
console.log("omg");
});
socket.on("connect_error", err => {
console.log("error", err);
});
}, []);
const handleSendReply = () => {
if (validateLength(replyText) === 0) {
setReplyTooShort(true);
return;
}
sendMessage(
replyText,
user.username
);
console.log("replyText", replyText); // prints
socket.emit("msg", replyText);
setReplyText("");
};
return <View>
<Input
label="reply"
value={replyText}
onChangeText={e => setReplyText(e)}
/>
<View style={{ alignItems: "flex-end" }}>
<Icon
name="md-send"
type="ionicon"
iconStyle={{ paddingLeft: 20, paddingRight: 20, paddingTop: 10 }}
onPress={() => handleSendReply()}
/>
</View>
</View>
}
"socket.io": "^2.3.0" // server
"socket.io-client": "^2.3.0" // client
Edit:
(The yellow warning should be ignored as per this comment)
Upvotes: 0
Views: 1463
Reputation: 196
Socket server listens on connection event.
When connection is successful a new socket object is created with a unique id.
This Socket object handles sending and receiving of events/data.
io.on("connection", (socket) => {
// console.log("Backend, connected!"); // user or client is connected.
console.log("User connected with a unique socketId ", socket.id);
socket.on("msg", function (msg) {
console.log("entered!"); // <--- It will print now !
console.log("message: " + msg);
});
});
Upvotes: 1