EngineIOException: xhr poll error in Android + Socket.io - android

I have the following error while trying to connect to localhost machine:
I/Connection error: Connectio errorio.socket.engineio.client.EngineIOException: xhr poll error
My code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import io.socket.client.IO;
import io.socket.client.Manager;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import io.socket.engineio.client.Transport;
public class LoiginActivity extends AppCompatActivity {
private Socket socket;
{
try {
socket = IO.socket("http://localhost:3000");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loigin);
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG,"connected");
}
});
socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "Connectin error" + args[0]);
}
});
socket.connect();
}
}
Internet permissons are set up. Using Socket.IO on android Always Returns XHR Poll Error didn't help me

In case someone is going through this.
try {
socket = IO.socket("http://localhost:3000");
} catch (URISyntaxException e) {
e.printStackTrace();
}
The OP is trying to connect to the localhost. In this case, localhost refers to the phone itself and probably the socket.io server is not on the phone. To solve this, change "http://localhost" with the machine's (that is serving socket.io) local network ip address.

Related

Connection Error in Socket.io in Native Android

I was creating a application using socket.io in native android application to communicate with websockets Tester. I have tested it using a online WebSocketServer , but each time when trying to check the connection in android device, 'Connection Error` is Logged.
Error : io.socket.engineio.client.EngineIOException: websocket error
java.net.ProtocolException: Expected HTTP 101 response but was '404 Not Found'
onlineTestingPortal link :https://www.piesocket.com/websocket-tester
SocketServerCode:
package com.example.appsocket;
import android.util.Log;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import io.socket.engineio.client.transports.WebSocket;
public class SocketServer {
private Socket mSocket;
private static SocketServer lbInstance = new SocketServer();
public static SocketServer getInstance() {
return lbInstance;
}
public void callSocketServer(){
try {
IO.Options options = new IO.Options();
options.transports = new String[]{ WebSocket.NAME};
mSocket = IO.socket("wss://demo.piesocket.com/v3/channel_123?api_key=VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV&notify_self",options);
mSocket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
System.out.println("Connection Error");
}
});
mSocket.connect();
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
System.out.println("SocketServer: connected call back" + args[0].toString());
mSocket.emit("YOUR_TOPIC", "YOUR_DATA_VALUE");
}
});
} catch (URISyntaxException e) {
System.out.println("Exception is : " + e);
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SocketServer.getInstance().callSocketServer();
}
}
Your problem is because of using socket.io library, you don't need socket.io.
In this link, the correct way to connect to ws protocol is mentioned

Connect android studio to azure sql database using Java

package com.example.workdb;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.Bundle;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.sourceforge.jtds.jdbc.*;
public class MainActivity extends AppCompatActivity {
public Button run;
public TextView message;
public TextView txtvw;
public Connection con;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
run= (Button) findViewById(R.id.button);
run.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
CheckLogin checkLogin= new CheckLogin();
checkLogin.execute("");
Log.d("CREATION","ON CREATE WORKS");
// Log.d("txtvw", connection);
//System.out.println("Yes");
// txtvw.setText("hello");
}
});
} public class CheckLogin extends AsyncTask<String,String,String>
{
String z="";
Boolean IsSuccess= false;
String name1="";
// Log.d("txtvw","step 1 done");
protected void onPostExecute(String r){
if (IsSuccess){
message=(TextView)findViewById(R.id.textView);
message.setText(name1);
Log.d("TAG", "STEP 1 DONE");
}
}
#Override
protected String doInBackground(String... strings) {
try
{
Connection con = connectionClass();
if(con==null){
z="Check interent";
//Log.d("txtvw", z);
}
else
{
String query= "select * from Value";
Statement stmt= con.createStatement();
ResultSet rs= stmt.executeQuery(query);
if (rs.next())
{
name1=rs.getString("KneeAngle");
Log.d("MYTAG", "name 1 works");
z="Query success";
IsSuccess=true;
con.close();
}
else{
z="Invalid query";
IsSuccess=false;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return z;
}
}
public Connection connectionClass(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL ;
try{
Class.forName("net.sourceforge.jtds.jdbs.Driver");
ConnectionURL="jdbc:jtds:sqlserver://havvasemserv3.database.windows.net:1433;DatbaseName=Newfin;user=;password=;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30";
connection= DriverManager.getConnection(ConnectionURL);
} catch(ClassNotFoundException e){
Log.e("Error here 2 ",e.getMessage());
}
catch (Exception e) {
Log.e("error here 3:",e.getMessage());
}
//Log.d("txtvw", connection);
return connection;
}
}
I am trying to connect azure sql database to android studio. I have added all the permissions in the manifest file and I have also added a jtds module 1.3.1 in the project and implemented it in the gradle module app. My code exits with 0 errors but data is not displayed on the emulator. Expected output is the first value from my database which is "8".
Thanks.,
Add this at the end of you current connection url after timeout=30
;ssl=request
Also make sure in your firewall settings of your azure server!/database your current device ip is allowed to access as by default all access is blocked,
To allow all devices to access server go to the firewall settings and in the insert ip section add this ip range
0,0,0,0 and 255,255,255,255

Android TCP Connection: accept() not working

I am building an Android app using TCP connection. Below is my TCP server code. When i test, it doesn't have any errors but the app has error
"unfortunately app has stopped".
When i check the code it stucks at:"
s=serverClient.accept();
Here is my code:
package com.example.truong.total;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by duy on 26/10/2017.
*/
public class TCPServer {
int port;
String result;
ServerSocket serverClient;
TextView tv5;
MainActivity at;
public TCPServer(int newPort,MainActivity at) {
this.port=newPort;
this.at=at;
try{
serverClient=new ServerSocket(port);
}catch(IOException e) {
e.printStackTrace();
}
Log.d("constructornethanglol","1");
//Log.d("constructornethanglol","1");
}
public void setConnection() {
tv5=(TextView)at.findViewById(R.id.textView5);
Log.d("thanglol","2");
try {
Log.d("lol3","3");
while (true) {
Log.d("lol4","4");
Socket s;
Log.d("thanglol1","socket");
//stuck
s=serverClient.accept();
Log.d("lol5","5");
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(s.getInputStream()));
this.result = inFromClient.readLine();
tv5.setText("lol");
s.close(); // sau khi dat. trong while
}
}catch(IOException e) {
e.printStackTrace();
}
}
public String getResult() {
return this.result;
}
}
Can you show me where am i wrong? Thank you. Sorry for my bad English, it's not my first language.
You should use networking related stuffs in a background thread. Either use AsyncTask or a Thread.
new Thread(new Runnable(
public void run(){
//your code.
}
)).start();
You can view an example at
https://github.com/nabinbhandari/android-socket-messaging

Can't connect to node server from android while i can from browser

i have created a node server that i wanna connect from different devices.
here is the code for server ...
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log(socket.id);
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(2000, function(){
console.log('listening on *:2000');
});
i can simply connect to the server by browser. but i can't connect using android device. here is my android side code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
public class MainActivity extends AppCompatActivity {
private Socket mSocket;
public Socket getSocket(){
if(mSocket==null){
try{
mSocket = IO.socket("http://localhost:2000");
}catch (Exception e){
e.printStackTrace();
Log.d("error connecting" , " to server");
}
}
return mSocket;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Socket socket = getSocket();
socket.connect();
}
}

webserver for file upload on android

I would like to add a webserver to my android application for uploading small files to the phone.
The user would start the webserver from the phone by hitting a button. He would then see an ip address that can be accessed by any browser from a pc. The website behind this ip address should show a file upload opportunity.
My question is: Is there an open source project similar to my needs? Or how would you recommend doing this?
you can use NanoHttpd link it's very weight android web server that is nicely embbedible..
package .....;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class AndroidWebServerActivity extends Activity {
private static final int PORT = 8765;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume() {
super.onResume();
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT, null);
}
#Override
public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
final StringBuilder buf = new StringBuilder();
for (Entry<Object, Object> kv : header.entrySet())
buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
handler.post(new Runnable() {
#Override
public void run() {
}
});
final String html = "<html><head><head><body><h1>Hello, World</h1></body></html>";
return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, html);
}
}
}

Categories

Resources