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.
Related
I am deploying my XF app at Android 4.4 and basing on this advise
I am trying to get a notification regarding established Wifi connection. I added CrossConnectivity.Current.ConnectivityChanged in my App.xaml.cs but this event seemed never happened when my application connected to a Wifi network. What did I do wrong? My code is the following:
public partial class App : Application {
public App (IWifiOperations mgr) {
InitializeComponent(); MainPage = new MainPage(mgr);
}
protected override void OnStart () {
CrossConnectivity.Current.ConnectivityChanged += Current_ConnectivityChanged;
}
private void Current_ConnectivityChanged(object sender, Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e) {
var qq = "";
}
}
I have started developing live streaming using kurento media server. I have Installed kurento media server in Ubuntu 14.04TLS. It gets successfully Installed and also started successfully.
I have used STUN server, I have uncommented these two lines
stunServerAddress=<stun_ip_address>
stunServerPort=<stun_port>
And used IP, PORT as follows: 173.194.66.127:19302
.After doing all these thing I started kurento media server and it gets started.
Now I create Android native application by implementing RoomListener Interface.
Here is the Code to connect with Kurento Media Server.
public class MainActivity extends AppCompatActivity implements RoomListener {
private LooperExecutor executor;
private static KurentoRoomAPI kurentoRoomAPI;
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
executor = new LooperExecutor();
executor.requestStart();
String wsRoomUri = "wss://173.194.66.127:19302/room";
kurentoRoomAPI = new KurentoRoomAPI(executor, wsRoomUri, this);
kurentoRoomAPI.connectWebSocket();
}
#Override
public void onRoomResponse(RoomResponse response) {
Log.d(TAG, "Response");
}
#Override
public void onRoomError(RoomError error) {
Log.d(TAG, "Error: " + error.toString());
}
#Override
public void onRoomNotification(RoomNotification notification) {
Log.d(TAG, "Notification Received");
}
#Override
public void onRoomConnected() {
Log.d(TAG, "Connected");
}
#Override
public void onRoomDisconnected() {
Log.d(TAG, "Room Disconnected");
}
}
But when I run the application, it shows the following error:
Process: com.base.videostreamingkurento, PID: 1880
java.lang.AssertionError: java.net.SocketTimeoutException: failed to connect to /173.194.66.127 (port 19302) after 90000ms
at libcore.io.IoBridge.connect(IoBridge.java:117)
at java.nio.SocketChannelImpl.connect(SocketChannelImpl.java:199)
at org.java_websocket.client.WebSocketClient.interruptableRun(WebSocketClient.java:210)
at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:188)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.net.SocketTimeoutException: failed to connect to /173.194.66.127 (port 19302) after 90000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:189)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:115)
It seems that you have a little confusion with your deployment and IPs. You are trying to connect, from your client, to the STUN server. Instead, try setting the IP and PORT where your app server is located in this line
String wsRoomUri = "wss://APP_SERVER_IP:8443/room";
If you can draw that down, you'll see more clearly where everything goes and what should connect to what.
Here's my situation: i have a server written with sails.js where i have a user model. I have a dashboard where i can see all the users, create new, delete them and so on...Now i want to create an android app where i can get, using socket.io, notification about the events that occour to the user model.
Example: if i delete a user from my dashboard i want the app to recive a notification from the server that the user has been deleted.
Here's my code for the app:
public class MainActivity extends Activity {
//socket instance
private Socket mSocket;
{
try {
mSocket = IO.socket("http://server_url:port/user");
} catch (URISyntaxException e) {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //set the layout for this activity
final TextView tv = (TextView) findViewById(R.id.textView);
mSocket.on("user", new Emitter.Listener() {
#Override
public void call(Object... args) {
tv.setVisibility(View.INVISIBLE);
}
});
mSocket.connect();
final Button btn_createUser = (Button)findViewById(R.id.button);
btn_createUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSocket.connected()) {
//tv.setVisibility(View.INVISIBLE);
}
}
});
}
}
Like i did with the dashboard to connect the socket to the server i did the same thing here, but it seems like the socket doesn't connect, in fact, when i delete a user from the dashboard i get no notification.
Here's the code (that works) i used in my dashboard to connect my socket to the server and listen to updates from the user model:
//connect to the server and listen to updates from user model
io.socket.get('/user', function(data, jwres) {
$scope.users = data;
$scope.$apply(); //write users in the table...
});
//wait for updates...
io.socket.on('user', function serverResponded (data) {
if(data.verb == "updated")
{
//get the user index in the array and update it
var index = getIndex(data.id, $scope.users);
$scope.users[index].online = data.data.online;
$scope.$apply();
}
if(data.verb == "destroyed")
{
//get the user index in the array and remove it
var index = getIndex(data.id, $scope.users);
$scope.users.splice(index, 1);
$scope.$apply();
}
if(data.verb == "created")
{
//simply update the array
$scope.users.push(data.data);
$scope.$apply();
}
});
Now, i think all i'm missing out in the android app is the GET request which automatically subscribe my socket to the model and get notified if something happen...but i don't know hot to do it.
I hope i was clear enough...thank to everyone who will answer me!
PS: i don't want to use AndroidAsync because i need the ultimate version of socket.io!
In case someone need it, i found the solution: https://github.com/balderdashy/sails/issues/2640 here you can find out how to solve the issue! :)
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.
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.