Flutter (emulator) doesn't connect to local Socket.io - android

I'm trying to connect to my local server in node.js with Socket.io using Flutter. It works ok when i connect from my browser, but it doesn't connect using my Android/iOS emulators. My socket.io code is pretty simple
// socket messages
io.on("connection", client => {
console.log("New device connected!")
// print in the console when some device disconnects
client.on("disconnect", data => {
console.log("disconnected!")
})
})
Flutter code (also pretty simple too):
IO.Socket socket = IO.io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
// Dart client
socket.on('connect', (_) {
print('connect');
});
socket.on('event', (data) => print(data));
socket.on('disconnect', (_) => print('disconnect'));
socket.on('fromServer', (_) => print(_));
It always displays "disconnect" every ~30 seconds (in flutter console), also in the node.js it never displays a "New device connected!"
What i'm using?
Flutter Socket.io Dependency
pubspec.xml
dependencies:
flutter:
sdk: flutter
socket_io_client: ^0.9.11
provider: ^4.3.2+2

There's different reasons of why this is not working, but here i describe a couple of them of how you can solve it.
First check if server is responding
Check if you can access it using your pc web browser, it should something like
Check if your device web browser have access
If both things are working fine, try with one of these solutions:
Solution #1
The url that you've tested in the emulator browser (not in your pc browser) is the same url that you need to use in your flutter app.
iOS
http://localhost:3000 # port can change, check your node.js config
http://<your_pc_ip:3000>:3000 # you can check it in the preferences or terminal -> ipconfig
Android
http://10.0.2.2:3000
http://localhost:3000 # port can change, check your node.js config
http://<your_pc_ip:3000>:3000 # you can check it in the preferences or terminal -> ipconfig
Solution #2
My node.js project was using socket.io version 3.0.0 (the latest), but it looks like my flutter client doesn't support it, so try to downgrade to version 2.3.0 (don't do it manually, in other words don't modify the file manually)
npm uninstall socket.io
npm install socket.io#2.3.0
and your package.json will be (in your node.js project)
"dependencies": {
"dotenv": "^8.2.0",
"express": "^4.17.1",
"socket.io": "^2.3.0"
}
Note: if you want to keep using socket.io version 3.0 instead of v2.3.0 then you should use the new version of flutter client (currently in beta): Flutter Client for Socket.io v3.0
Solution #3
For some reason the "autoConnect" not always work, so try to connect it manually.
IO.Socket socket = IO.io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': true,
});
// Dart client
socket.on('connect', (_) {
print('connect');
});
socket.on('event', (data) => print(data));
socket.on('disconnect', (_) => print('disconnect'));
socket.on('fromServer', (_) => print(_));
// add this line
socket.connect();
Solution #4
Maybe there's a firewall or something blocking your port (mine 3000), try to run it using another port. You need to change the config in your server and also change the url in the flutter app (also test it using your emulator/simulator browser)
and that's it... it should work.
You should see something like:
Flutter
Server

I had the same Issue using socket_io_client.
Using :Socket socket = io(SERVER_ADRESS, <String, dynamic> { 'transports':['websocket'], 'autoConnect' : true}); instead of : Socket socket = io(SERVER_ADRESS);.

Related

React-Native Connect FaunaDB, TypeError: Network request failed on Android

I want to connect to faunadb through the application I developed with React native.
For this, I installed faunadb's node.js package and prepared the necessary queries.
The processes I did worked on IOS without any problems. But I am getting the following error on android:
Possible Unhandled Promise Rejection (id: 0):
TypeError: Network request failed
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.
...
I have the same issue on android both emulator and real device.
I tried the following to solve the problem:
https://github.com/facebook/react-native/issues/32931
Due to Android restrictions, a network_security_config configuration must be added to the application. It is an xml file that can be added by following these steps:
Edit the android/app/src/main/AndroidManifest.xml
Add the android:networkSecurityConfig="#xml/network_security_config" to the tag
Create the folder android/app/src/main/res/xml and inside a file called network_security_config.xml
If you don't want to install the CA in the Android certificates, add the folder android/app/src/main/res/raw
But nothing changed.
Here are my connection settings to FaunaDB:
import faunadb from 'faunadb';
const client = new faunadb.Client({
secret: process.env.FAUNA_KEY,
domain: 'db.fauna.com',
});
const q = faunadb.query;
export {client, q};
The reason why I am specifically mentioned here as faunaDB is that when I want to connect to another api and pull data, I don't have any problems.
For example, in the fetch example below, the movie list returns successfully.
fetch('http://facebook.github.io/react-native/movies.json')
.then(response => response.json())
.then(responseJson => {
console.log(responseJson.movies);
})
.catch(error => {
console.error(error);
});
What am I missing here? Thanks in advance for your ideas and help.
I found the solution to the problem, I wanted to report it here.
For the solution, I defined the header setting to the faunaDB client and it was enough to send 'Content-Type': 'application/json' in the header.
The final version of my FaunaDB client code is as follows:
import faunadb from 'faunadb';
const client = new faunadb.Client({
secret: process.env.FAUNA_KEY,
domain: 'db.fauna.com',
scheme: 'https',
headers: {
'Content-Type': 'application/json',
},
});
const q = faunadb.query;
export {client, q};

Expo/RN: fetch from Android App behind corporate proxy

I am building an app using Expo (SDK 47) which I am running in the standard Android emulator.
My development machine is behind a corporate proxy with a custom certificate. I have:
Installed the certificate on my machine (Macbook)
Installed the certificate in the Android image
Added the necessary proxy config to Android Studio and configured the Android emulator to use the same config.
I have verified that:
Outgoing traffic works fine in the native browser
Outgoing traffic works fine when running Chrome in the Android emulator
HOWEVER, whenever I try to make fetch requests to external sites from the app itself, it fails due to certificate errors:
import axios from 'axios'
const createInstance = (baseURL) => {
return axios.create({
baseURL,
headers: {
"Content-Type": "application/json"
}
})
}
const axiosConfig = createInstance('https://api.outside.com/');
export const getToken = (body) => {
axios.post('some/endpoint', body)
.then((res) => {
console.log(res);
})
.catch((e) => {
console.log("error", e);
})
};
getToken(body);
Error is:
AxiosError: Network Error
Which I can only assume is due to the proxy - we are NOT seeing the problem when testing on a public network.
How do I go about making sure my app correctly uses the certificates provided by its host?

Connection to mysql database failed while trying to run ionic project on android

I am trying to run an ionic application using nodejs as server to connect to mysql database on android , the application runs perfectly on lab but when it comes to android it failed to connect to localhost , apparently the emulator couldn't recognize the address am using .This is the code am using in my ionic service :
export class CandidatService {
base_path = 'http://10.0.2.2:1617';
constructor(private http: HttpClient) { }
// Http Options
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
getAllCandidats(): Observable<Candidat[]>
{
return this.http
.get<Candidat[]>(this.base_path+"/selectAllCandidats", this.httpOptions)
.pipe()
}
}```
is this ip and port is the valid nodejs server app?
http://10.0.2.2:1617
do you have console.log on what happen on the nodejs ?
is your nodejs server and your android is running on same wifi ?
if no, then you might need to use public ip
or the simple one is using ngrok
reference : https://ngrok.com/

cordova-plugin-chrome-apps-socket plugin throw chrome undefine Error

I create ionic 3 application and I want send and receive data between two app with hotspot network and I try to create client and server socket on each app with this plugin :
npm i cordova-plugin-chrome-apps-socket
and try with this code :
declare var chrome;
and use plugin in ionViewDidLoad :
ionViewDidLoad(){
chrome.sockets.tcp.create({}, createInfo => {
let socketTcpId = createInfo.socketId;
chrome.sockets.tcp.connect(socketTcpId, "127.0.0.1", 12345, result => {
console.log("Connected to server");
});
});
}
and run :
ionic cordova build android
and install and run apk file on genymotion but console give me this error :
chrome is not defined
and also I try with this way :
ionViewDidLoad(){
(<any>window).chrome.sockets.tcp.create({}, createInfo => {
socketTcpId = createInfo.socketId;
chrome.sockets.tcp.connect(socketTcpId, "127.0.0.1", 12345, result => {
console.log("Connected to server");
});
});
}
but console give me last error
You need to install following TCP library
cordova-plugin-chrome-apps-sockets-tcp

Using Android UIAutomator in Python or Ruby

I am trying to automate android apps using python (or possibly ruby), by linking into the provided UIAutomator in the android SDK.
Right now I am trying to use a Python tool here, but I am having issues connecting (getting TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
Code snipped of what i am trying to do with the Python tool:
def print_info():
print('Getting info...')
d = ui.Device('SERIAL_NUMBER', adb_server_host='192.168.1.20', adb_server_port='5037')
print(d.info)
Is there something wrong with how I am trying to send commands? Alternatively, is there a better ruby/python tool for testing android devices?
Update I am now using the Appium library Ruby gem to test. Got applications to launch, however things like tapping the screen result in this error
assert_ok': A session is either terminated or not started
(Selenium::WebDriver::Error::NoSuchDriverError)`
This is the code
desired_caps = {
caps: {
appiumVersion: '1.6.5',
platformName: 'Android',
platformVersion: '4.4',
browserName: '',
deviceName: 'DEVICE_SERIAL',
app: 'APK',
appActivity: 'mainactivity',
appWaitDuration: '60000', # wait a minute (set to 20000 by default)
clearSystemFiles: 'true'
},
appium_lib: {
sauce_username: nil,
sauce_access_key: nil
}
}
$driver = Appium::Driver.new(desired_caps)
$driver.start_driver
sleep(60) # wait a minute for app to fully load, before tring to tap anything
touch_action = Appium::TouchAction.new
touch_action.press(x: 243, y: 288).wait(5).release.perform
touch_action.press(x: 311, y: 165).wait(5).release.perform
This is how I do it for an emulator
app_path = File.absolute_path('automateme.apk', 'data')
caps = {
:platformName => "android",
:deviceName => "android",
:app => app_path,
:noReset => 'true',
:newCommandTimeout => "30"
}
#driver = Appium::Driver.new(:caps => caps).start_driver
try this and let me know if it helps... :)
There is an one good mobile test automation tool available - Appium.
Currently I have been using ruby,appium,cucumber,selenium webdriver for android automation. I am suggesting that you will try to use Appium tool for mobile automation. below is important link,
http://www.software-testing-tutorials-automation.com/2015/09/appium-tutorials.html
https://community.perfectomobile.com/posts/1103155-ruby-example-for-appium-android
http://appium.io/slate/en/tutorial/android.html?ruby#troubleshooting
following is the example to start
require 'appium_lib'
desired_caps = {
caps: { appiumVersion: '1.6.0',
platformName: 'Android',
platformVersion: '4.4.2',
browserName: '',
deviceName: 'Samsung Galaxy S4 Emulator',
app: 'D:\Workspace\android-sample-app.apk',
name: 'Ruby Appium Sauce example'
} }
driver = Appium::Driver.new(desired_caps)
puts driver
begin
driver.start_driver
rescue Exception => e
puts e
end
driver.first_textfield.send_key 10
driver.last_textfield.send_key 20
driver.first_button.click
driver.driver_quit
download "android-sample-app.apk" and put in any path and also set this path
in desired_caps.
Thanks,
Kapil Chothe

Categories

Resources