Connection Error in Socket.io in Native Android - 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

Related

Error connecting: io.socket.engineio.client.EngineIOException: xhr poll error

I am trying to use socket.io to connect to the Nodejs server and Android client. I am getting the xhr poll error when trying to connect. I have seen such issues raised by other people, but with no solution. I have socket io 2.1.1 on node server and using 'io.socket:socket.io-client:0.8.3' in Android. My Android version is Oreo.
This is my Android client code:
package com.example.socketiodemo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import io.socket.client.IO;
import io.socket.client.Manager;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends AppCompatActivity {
private TextView display_text;
private Socket mSocket;
Manager mManager;
private boolean fClientClosedConnection;
private boolean fClientIsConnected;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
display_text = (TextView)findViewById(R.id.display_text);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
fClientClosedConnection = false;
fClientIsConnected = false;
new MyAsyncTask(mSocket).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyAsyncTask extends AsyncTask<String, Void, String> {
Socket mSocket;
Manager mManager;
MyAsyncTask(Socket socket) {
mSocket = socket;
}
#Override
protected String doInBackground(String... params) {
Log.e(TAG, "Initiating the connection");
try {
mSocket = IO.socket("http://192.168.0.104:4444");
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onTimeoutError);
mSocket.on(Socket.EVENT_ERROR, onError);
mSocket.on("data", onNewMessage);
mSocket.connect();
while (!fClientClosedConnection) {
// Keep the thread active
}
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
Log.e(TAG, "Finished the background Process");
return "";
}
#Override
protected void onPostExecute(String result) {
mSocket.close();
}
}
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "onConnect");
if(!fClientIsConnected) {
Toast.makeText(getApplicationContext(),
"Client is connected", Toast.LENGTH_LONG).show();
fClientIsConnected = true;
}
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "diconnected");
fClientIsConnected = false;
Toast.makeText(getApplicationContext(),
"Client is disconnected", Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Error connecting: " + args[0].toString());
Toast.makeText(getApplicationContext(),
"Client connect error", Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onTimeoutError = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Timeout Error ");
}
});
}
};
private Emitter.Listener onError = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Error ");
}
});
}
};
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String message;
try {
message = data.getString("message");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
printMessage(message);
if (message.contentEquals("Bye"))
{
fClientClosedConnection = true;
}
}
});
}
};
private void printMessage (String message)
{
display_text.setText(message);
}
}
This is my nodejs server:
process.title = 'node-android';
var app = require('http').createServer()
var io = require('socket.io')(app);
app.listen(4444, onListenStart);
io.on('connection', onConnect);
function onListenStart()
{
console.log("Server listening on port: " + SERVER_PORT);
}
function onConnect(client)
{
console.log("client is connected");
client.emit("data", { message: 'Hello'});
client.on('event', onMessageReceived);
client.on('disconnect', onDisconnect);
}
function onMessageReceived(data)
{
console.log(data);
}
function onDisconnect()
{
console.log("client is disconnected");
}
I get these logs:
05-20 21:48:56.404 28026-28026/com.example.socketiodemo E/MainActivity: Error connecting: io.socket.engineio.client.EngineIOException: xhr poll error
05-20 21:48:57.921 28026-28026/com.example.socketiodemo E/MainActivity: Error connecting: io.socket.engineio.client.EngineIOException: xhr poll error
Please help, as I have been stuck on this since 3 days.
I have socket io 2.1.1 on node server and using 'io.socket:socket.io-client:0.8.3'
I had similar situation, changing library version to 1.0.0 helped.
you must add this code in application tag in manifest like below,
It solved Error connecting: io.socket.engineio.client.EngineIOException: xhr poll error
same issues
<Application . . android:usesCleartextTraffic="true"> . . . <Application/>

EngineIOException: xhr poll error in Android + Socket.io

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.

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();
}
}

Sending IM to gmail account over XMPP

I've recently read about XMPP and I would like to make an application which can send and receive IM messages so that I could get some experience with using XMPP. The problem is I hardly know anything about using XMPP or about using it with Android. I was wondering if someone could point me in the right direction on how to use XMPP with Android.
Thanks!
Well to start with XMPP you have to
Install OpenFire (The chat server)
Add the smack.jar XMPP client jar into the Android app
Implement the PacketListener like such
public class MyPacketListener implements PacketListener {
#Override
public void processPacket(Packet packet) {
// Write the implementation code here.
//The packet contains the message and the metadata about the message.
}
}
4.Next you need to implement the to handle the connection fail gracefully as such.
public class XMPPConnectionFailedException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public String toString() {
return "The Chat server or the Connection to the chat server failed";
}
}
5.Next you would need the class that actually does the connecting to the XMPP server and here is a implementations
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smackx.PrivateDataManager;
import com.test.chat.MyPacketListener;
import com.testchat.exception.XMPPConnectionFailedException;
public class ChatUtil {
public final static String SERVER_HOST = "serverip";
public final static int SERVER_PORT = 5222;
public final static String SERVICE_NAME = "p2547738.pubip.serverbeach.com";
private static XMPPConnection xmppConnection;
public static String CURRENT_RECIPIENT_CHAT_ID;
public static String CURRENT_RECIPIENT_NAME;
public static final String IN = "IN";
public static final String OUT = "OUT";
public static String CURRENT_RECIPIENT_FB_IMAGE;
public static boolean STARTED = false;
public static XMPPConnection getXmppConnection(String username) throws XMPPConnectionFailedException {
try {
if (xmppConnection == null) {
ConnectionConfiguration config = new ConnectionConfiguration(SERVER_HOST, SERVER_PORT, SERVICE_NAME);
xmppConnection = new XMPPConnection(config);
}
if (!xmppConnection.isConnected()) {
xmppConnection.connect();
}
if (!xmppConnection.isAuthenticated()) {
xmppConnection.login(username, "123");
ProviderManager pm = ProviderManager.getInstance();
pm.addIQProvider("query", "jabber:iq:private",new PrivateDataManager.PrivateDataIQProvider());
PacketFilter packetFilter = new MessageTypeFilter(Message.Type.chat);
xmppConnection.addConnectionListener(new ConnectionListener() {
#Override
public void reconnectionSuccessful() {
System.out.println("reconnectionSuccessful");
}
#Override
public void reconnectionFailed(Exception arg0) {
System.out.println("reconnectionFailed");
}
#Override
public void reconnectingIn(int arg0) {
System.out.println("reconnectingIn");
}
#Override
public void connectionClosedOnError(Exception arg0) {
System.out.println("connectionClosedOnError");
}
#Override
public void connectionClosed() {
System.out.println("connectionClosed");
}
});
MyPacketListener listener = new MyPacketListener();
xmppConnection.addPacketListener(shareFareChatListener,packetFilter);
}
Presence presence = new Presence(Presence.Type.available);
xmppConnection.sendPacket(presence);
ChatUtil.STARTED = true;
} catch (Exception e) {
throw new XMPPConnectionFailedException();
}
return xmppConnection;
}
}
6.Finally you try to connect your to the XMPP server using the credentials you used to sign users up as such
private void connectToChat(final String nickname) {
System.out.println("Connect to chat ...");
class ConnectToChatAsync extends AsyncTask {
#Override
protected Integer doInBackground(Context... params) {
try {
Listener.currentActivity = context;
ChatUtil.getXmppConnection(nickname);
return SERVER_SUCCESS_RESPONSE;
}
catch ( XMPPConnectionFailedException e) {
System.err.println("XMPPConnectionFailedException : " + e);
}
return CONNECTIVITY_PROBLEM;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if(result == CONNECTIVITY_PROBLEM){
// ApplicationDialog.showFeedBackDialog(ProjectConstants.XMPP_CHAT_FAILED, context);
}
}
}
new ConnectToChatAsync().execute();
}
That should settle you Programatically, all you got to do is Setup the Openfire Environment.
These links should help you out on that department
Create Your Own Jabber-Based Server That Works With iChat or Any Jabber Client
DIY: Set up the Openfire internal chat server

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