【发布时间】:2021-02-10 11:45:07
【问题描述】:
所以我有一个运行良好的 electron-express-socket.io 应用程序。 我现在需要使用 ("socket.io-client") 将 EXPO 应用程序连接到 socket.io。
它们位于不同的端口。
- Eelectron-express-socket.io = http://localhost:3000/
- EXPO 应用程序 = 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);
}
}
世博APP:
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"
}
}
}
});
【问题讨论】: