This question is related to How to build a Maven Android project in eclipse. Using suggestions from #user714965 I was able to build the code in project : https://github.com/nkzawa/socket.io-client.java. Now I am trying to compile an Android test project. I created a new Android project and under Java Build Path specified the socket.io-client project as dependency. But I am getting compilation errors. Eclipse is unable to find Emitter Class.
This is the relevant code:
public class SocketTask extends AsyncTask<Void, Void, Void> {
Socket mSocket = null;
#Override
protected Void doInBackground(Void... arg0) {
try {
Log.d(TAG, "Connecting to server");
mSocket = IO.socket("<my tested socket.io server address>");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Connected");
}
}).on("event", new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Event");
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Disconnect");
}
});
mSocket.connect();
return null;
}
}
It looks like dependent libraries are not resolved. Did you install all of them correctly?
engine.io-client 0.3.0
Java-WebSocket 1.3.0
org.json 20090211 (installed in Android as default)
Emitter is included in engine.io-client.
I cannot respond to the comments (new StackOverflow user) but I have gotten the library to work in Android Studio via build.gradle. If you are primarly developing for Android they suggest moving to Android Studio as it will soon be the supported IDE.
EDIT
I can connect to a socketIO server built on nodejs from an android application with this library from nkzawa. Reference to repository.
Add library as gradle dependency:
compile 'com.github.nkzawa:socket.io-client:0.3.0'
I wrote a class to hold my socket:
public class SocketIO{
Socket sock = null;
public SocketIO(){
try{
sock = IO.socket('<connection string>');
//Place all events here as per documention
sock.on(Socket.EVENT_CONNECT, new Emitter.Listener(){
#Override
public void call(Object... args){
System.out.println("connect");
}
});
sock.connect();
} catch(URISyntaxException e){
e.printStatckTrace();
}
};
//Helper function for emiting from android
public void sEmit(String event, JSONObject obj){
if(socket.connected()){
sock.emit(event, obj);
}
}
}
And use it in my activity:
SocketIO socket = new SocketIO();
I had some initial trouble getting the library to work but it has been flawless since, the "issues" section of the github repository is very helpful.
Hope that helps.
Related
I have a problem when i try to go back from a cordova plugin integrated on cordova. When i try to do it, the app crashes, I debugged first the javascript and then the native code that javascript call and this is the instruction that make app crash.
cordova.getActivity().finish();
This is in TestPlugin.java file in this most global context:
if (action.equals("open")) {
try {
cordova.getThreadPool().execute(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(cordova.getActivity(),
PhemiumEnduserActivity.class);
cordova.getActivity().startActivity(intent);
cordova.getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
});
callback.success("");
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
else if( action.equals("exit_app") ) {
try {
cordova.getThreadPool().execute(new Runnable() {
#Override
public void run() {
cordova.getActivity().finish();
}
});
callback.success("");
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
When the app calls the plugin executes the "open" part and when i click the back button makes the "exit_app" part and then on cordova.getActivity().finish(); app crashes with no error on the android studio console. There is no signal of webview close. What i'm doing wrong? Why it crashes?
Please post full plugin code or repository, but i think is because you try to finish activity in another thread, or activity no more exist (getActivity return null).
You need to try with somewhat like this:
protected Activity mActivity;
....
else if( action.equals("exit_app") ) {
mActivity = cordova.getActivity();
try {
cordova.getThreadPool().execute(new Runnable() {
#Override
public void run() {
if(mActivity!=null)
mActivity.finish();
}
});
callback.success("");
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
For more trace info try to open android project in Android studio and debug it.
I'm using Android native socketio library and NodeJS.
// on my Android activity
private Socket mSocket;
{
try {
mSocket = IO.socket("http://IP_OF_MY_SERVER");
} catch (URISyntaxException e) {}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSocket.connect();
}
.
// on my nodejs app
var restify = require('restify');
var server = restify.createServer({
name: 'myapp',
version: '1.0.0'
});
var io = require('socket.io')(server.server);
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
io.on('connection', function(socket){
console.log('a user connected');
socket.on('new-item', function(data) {
console.log(data);
});
});
I'm following official guides but still mSocket.connect() not emitting connection event and there is no a user connected on my console when I launch activity.
Can you please tell me what is I'm missing and how can I debug it?
EDIT
NodeJS app on my Ubuntu server : http://paste.ubuntu.com/14233470/
Android activity : http://paste.ubuntu.com/14233482/
EDIT 2
I've changed my code like suggested here:
var io = require('socket.io').listen(server);
And this time I'm getting this error when I launch the activity
myapp listening at http://104.131.99.145:3000
http.js:691
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
at ServerResponse.format (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/response.js:145:10)
at ServerResponse.send (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/response.js:338:14)
at emitRouteError (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:201:13)
at onRoute (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:754:21)
at Router.find (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/router.js:608:5)
at Server._route (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:747:21)
at routeAndRun (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:705:14)
at Server._handle (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:725:9)
at Server.onRequest (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:326:14)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at Socket.socket.ondata (http.js:1966:22)
at TCP.onread (net.js:525:27)
A few key notes:
Create a Socket object:
private Socket mSocket;
{
try {
mSocket = IO.socket(CHAT_SERVER_URL); // Your server's URL
}
catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
onCreate(): connect & set the socket error listener
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.connect();
}
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Unable to connect to NodeJS server", Toast.LENGTH_LONG).show();
}
});
}
};
Disconnect the Socket in the onDestroy() method
#Override
protected void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
}
Not getting the error toast is the first milestone to setting this up right.
Create a WLAN:
(Open the command line with admin privileges, run these commands:)
netsh wlan set hostednetwork mode=allow ssid=NodeSocket key=1234okok
netsh wlan start hostednetwork
Make sure that your Android device is connected to this network, & that your Node.js server is up & running.
I am following a quick guide from Smack Documentation, for me to connect my asmack xmpp client with openfire xmpp server. But unfortunately, there a exception errors that I got from following the codes on smack documentation.
Since that I am not actually using smack but instead I am using asmack (smack version for android), I read from here that I should call SmackAndroid.init(Context)in order to initialize Smack on Android or Smack won't work as expected.
I aslo build add and dnsjava library, for me to execute this single line of code SmackAndroid.init(Context). I Thought that these steps will solve my problem upon connecting asmack client with openfire server but its not.
Here is my code:
public class MainActivity extends Activity {
public static final String HOST = "Kirbys-Mac-mini.local";
public static final int PORT = 5222;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ConnectToServer().execute();
}
private class ConnectToServer extends AsyncTask <Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
SmackAndroid.init(MainActivity.this);
boolean isConnected = false;
ConnectionConfiguration config = new ConnectionConfiguration(HOST, PORT);
XMPPConnection conn2 = new XMPPTCPConnection(config);
try {
conn2.connect();
isConnected = true;
}
catch (IOException e){
Log.e("XMPPIOExceptionj", e.toString());
} catch (SmackException e){
Log.e("XMPPSmackException", e.toString()+" Host:"+conn2.getHost()+"Port:"+conn2.getPort());
} catch (XMPPException e){
Log.e("XMPPChatDemoActivity", "Failed to connect to "+ conn2.getHost());
Log.e("XMPPChatDemoActivity", e.toString());
}
return null;
}
After I run the application, Errors will show up in my logcat because there is something wrong happened while connecting to my server. These are the error that was catched by the exception:
11-26 04:24:19.783: E/XMPPSmackException(3964): org.jivesoftware.smack.SmackException$ConnectionException Host:nullPort:0
I don't now why is this happening to my app. Even the way that I setup my openfire is on default and I also use its embedded database. Please help me with my problem.
I've got a Andriod Studio project and I'm trying to use the SocketIOClient from the AndroidAsync library. I'm building the library with the command:
dependencies {
compile 'com.koushikdutta.androidasync:AndroidAsync:1.0.0'
}
I was able to get the websocket example to work, but there's seems to be a version issue with the 1.0 and the SocketIOClient example. I've also tried using the 2.0 jar file, but SocketIOClient doesn't appear to be defined there at all(this is one of my first andriod applications, so maybe I'm just doing something wrong). Does anyone know what needs to be done to get the following code to compile:
SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), "http://192.168.1.2:3000", new ConnectCallback() {
#Override
public void onConnectCompleted(Exception ex, SocketIOClient client) {
if (ex != null) {
ex.printStackTrace();
return;
}
client.setStringCallback(new StringCallback() {
#Override
public void onString(String string) {
System.out.println(string);
}
});
client.on("someEvent", new EventCallback() {
#Override
public void onEvent(JSONArray argument, Acknowledge acknowledge) {
System.out.println("args: " + arguments.toString());
}
});
client.setJSONCallback(new JSONCallback() {
#Override
public void onJSON(JSONObject json) {
System.out.println("json: " + json.toString());
}
});
}
});
Thanks,
Scott
Just starting in Android dev, I would like to use Android Websockets code in my new project in Android Studio.
OS X 10.8.x, AS 0.4.0
I followed: How to import eclipse library project from github to android studio project?
Everything worked great until I tried to actually code. I pasted in (from the example):
List<BasicNameValuePair> extraHeaders = Arrays.asList(
new BasicNameValuePair("Cookie", "session=abcd")
);
WebSocketClient client = new WebSocketClient(URI.create("wss://irccloud.com"), new WebSocketClient.Listener() {
#Override
public void onConnect() {
Log.d(TAG, "Connected!");
}
#Override
public void onMessage(String message) {
Log.d(TAG, String.format("Got string message! %s", message));
}
#Override
public void onMessage(byte[] data) {
Log.d(TAG, String.format("Got binary message! %s", toHexString(data)));
}
#Override
public void onDisconnect(int code, String reason) {
Log.d(TAG, String.format("Disconnected! Code: %d Reason: %s", code, reason));
}
#Override
public void onError(Exception error) {
Log.e(TAG, "Error!", error);
}
}, extraHeaders);
client.connect();
// Later…
client.send("hello!");
client.send(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF });
client.disconnect();
When I build/run the project, I get:
error: cannot find symbol class WebSocketClient
I think my question is: What is the import statement I should use?
How would I go about adding/using this code?
You ran into a bug that was fixed in Android Studio 0.4.3. I recommend you upgrade.
The auto importer was broken. Once I restarted Android Studio it showed I should put:
import com.codebutler.android_websockets.WebSocketClient;
As my import. Now I have a NullPointerException for a particular piece of code, but that's a different problem.