I am trying to connect to a phoenix websocket backend from a mobile application, using React Native. For some reason the mobile side does not connect, while the web side is working fine.
The api side is fine, I can log with the mobile, or with the web client. But I cannot open the socket from the mobile part.
I copied phoenix.js, from master branch, and added it to the mobile client. I use this code to connect
const ROOT_SOCKET = 'ws://localhost:4000';
socket = new Socket(`${ROOT_SOCKET}/socket`, socketOptions);
While on the web side, I connect just with
socket = new Socket('/socket', socketOptions);
Adding some log, I see mobile does not even reach the connect method of the user socket. I tried also to use http:// instead of ws, but with no luck.
Do I need to specify some sort of origin? There should be no need to use CORS for websocket.
Is there a specific step to take in order to connect mobile application to the phoenix backend with websocket?
Your Socket probably has default settings, as far as I can tell there is no easy way to limit origin for native app clients so you’d have to relax the origin check, in your socket file (probably user_socket.ex) add check_origin: false to the transport:
transport :websocket, Phoenix.Transports.WebSocket, check_origin: false
make sure you do something against DOS in this case, like requests throttling, especially for the actions that query database or do some heavy lifting.
That’s strange, we use this setup with react native apps and it works. What response do you get in your native frontend? Can you connect to some sample public websocket (eg http://demos.kaazing.com/echo/)? If your server is available over the internet you can also check if another app can connect to it this way.
Our var on the native client side for local environments is the same as yours "ws://localhost:4000/socket".
Is there a an official method to include phoenix socket support other than just copying the file, and importing it?
We use the node package: "phoenix": "1.2.1", in the package.json and then in the API service we use it like that import {Socket} from 'phoenix';. After that you can instantiate it normally. Not sure it’s official but I think it’s better then reaching for external directory (I also did it at first).