[英]socket.io is not able to connect react-native and nodejs
我正在尝试在nodejs和react-native之间建立websocket连接。 但不幸的是,它不起作用。
问题是客户端没有通过 sockets 与服务器连接。
这是nodejs(服务器端)代码
const express = require('express');
const app = express();
var server = app.listen(3000, () => console.log('server connected'))
const io = require("socket.io")(server)
io.on("connect", (socket) => {
console.log("user connected");
socket.on("chat message", mssg => {
console.log(mssg);
io.emit("chat message", mssg)
})
})
app.get('/', (req, res) => {
res.send("Hey! u are connected to server");
})
这是本机(客户端)代码
import React from 'react'
import { Button } from 'react-native'
import io from 'socket.io-client'
export default class extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.socket = io("http://localhost:3000");
this.socket.on('connect', () => console.log("connected"))
this.socket.on("chat message", mssg => {
console.log("mssg recieved in client:", mssg)
})
}
render() {
return <Button title="click to send message" onPress={() => {
this.socket.emit("chat message", "anshika this side")
}
} />
}
}
使用的库:react-native 版本:0.62.1,socket.io-client 版本:2.3.0(客户端),socket.io 版本:2.3.0(服务器端)
我通过添加笔记本电脑的 ip 地址而不是将localhost
作为 react-native 代码中的链接解决了这个问题
您必须使用您的 ipv4 地址,并且要注意的是在 io 中将“传输”参数指定为 ['websocket'] 在 web 应用程序中不需要什么
import io from 'socket.io-client'
io('http://xxx.xxx.x.xxx:port', {
transports: ['websocket']
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.