Reputation: 69
Although the Web implementation works, the android emulator as well as my device does not connect to WebSocket. The following event error code is received where the error is thrown and then disconnected:
connection error
Event {
"isTrusted": false,
"message": "Failed to connect to /127.0.0.1:8000",
}
connection closed
Event {
"isTrusted": false,
"message": "Failed to connect to /127.0.0.1:8000",
}
Upvotes: 4
Views: 3047
Reputation: 301
I am also facing the similar issue for creating websocket connection, however it is working fine for echo websocket server:
const ws = new WebSocket('wss://echo.websocket.org'); Working fine
But not working at local: const ws = new WebSocket('ws://127.0.0.1:8000'); generating below error: ERROR WebSocket error: {"isTrusted": false, "message": "Failed to connect to /127.0.0.1:8000"} LOG WebSocket closed
Client Technology: React Native
const App = () => {
console.log("App function started");
useEffect(() => {
console.log("Websocket connection initiated");
const ws = new WebSocket('ws://127.0.0.1:8000');
ws.onopen = () => {
console.log('WebSocket connected');
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
ws.onmessage = (e) => {
console.log('Received message:', e.data);
};
ws.onclose = () => {
console.log('WebSocket closed');
};
// Clean up the WebSocket connection on component unmount
return () => {
ws.close();
};
}, []);
return ( <Text>This is working here</Text>
// Your app components here
);
};
Backend Technology: Laravel-10
Upvotes: 1
Reputation: 1
I'm pleased to inform you that I've found a solution that worked for me! To resolve the issue, you can use the following command:
adb -s devicename reverse tcp:3000 tcp:3000
This command is incredibly useful when you need to access a service running on your computer from your Android device. Specifically, it reverses port 3000 on your Android device to port 3000 on your computer.
I hope this helps you, and if you have any further questions or insights, please don't hesitate to share them. Your input could be invaluable to others experiencing a similar issue.
Upvotes: 0
Reputation: 344
@sib mentions the right ip but not the correct reason.
The reason why you need 10.0.2.2 on Android is that that's how you access the localhost via the android emulator. See the Android Docs.
On the iOs Emulator, you (should not) get the error, because there you access localhost on 127.0.0.1 as most people would anticipate
Upvotes: 1
Reputation: 69
The default websocket port for android emulator is the following, which is different from web.
android: "http://10.0.2.2:8000",
web: "http://127.0.0.1:8000",
Upvotes: 1