所以我有一个电子表达插座。IO应用程序运行良好。我现在需要将EXPO应用程序连接到插座。IO with ("socket.io-client").
它们在不同的端口。
- Eelectron-express-socket。io = http://localhost:3000/
- EXPO app = http://localhost:19006/
我试过了https://socket.io/docs/v2/handling-cors/
电子:
const socketio = require('socket.io');
class WebSocket {
socket = null
allClients = [];
socketOptions = {
'path': '/ws',
'pingInterval': 10000,
"handlePreflightRequest": (req, res) => {
res.writeHead(200, {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Methods": "GET,POST",
"Access-Control-Allow-Headers": "my-custom-header",
"Access-Control-Allow-Credentials": false
});
res.end();
}
}
constructor(httpServer) {
//-------------------------------------------------------
// this.socket = socketio(httpServer, this.socketOptions);
//-------------------------------------------------------
this.socket = socketio();
this.socket.attach(httpServer, this.socketOptions);
//-------------------------------------------------------
this.socket.on('connection', (client) => {
this.onConnection(client);
});
this.socket.on('error', this.onClientError);
}
}
世博会应用:
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:3000/";
export default function App() {
//-- SocketIO
const [response, setResponse] = useState("");
useEffect(() => {
const socket = socketIOClient(ENDPOINT, {
withCredentials: false,
});
socket.on("currentTime", data => {
setResponse(data);
});
}, []);
//-- SocketIO
return (
<View style={styles.container}>
<Text>{response}Open up App.js to start working on your app!</Text>
<StatusBar style="auto" />
</View>
);
}
我也累了
socketOptions = {
'path': '/ws',
'pingInterval': 10000,
"handlePreflightRequest": (req, res) => {
res.writeHead(200, {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Methods": "GET,POST",
"Access-Control-Allow-Headers": "my-custom-header",
"Access-Control-Allow-Credentials": true
});
res.end();
}
}
和
const socket = socketIOClient(ENDPOINT, {
withCredentials: true,
transportOptions: {
polling: {
extraHeaders: {
"my-custom-header": "abcd"
}
}
}
});
我所要做的就是将EXPO更改为socket:
const socket = socketIOClient(ENDPOINT,{
path: '/ws',
});