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/>
Related
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¬ify_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
The Image shows the dashboard of the application
package com.example.leeyueloong.proximityapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.estimote.mustard.rx_goodness.rx_requirements_wizard.Requirement;
import com.estimote.mustard.rx_goodness.rx_requirements_wizard.RequirementsWizardFactory;
import com.estimote.proximity_sdk.proximity.EstimoteCloudCredentials;
import com.estimote.proximity_sdk.proximity.ProximityContext;
import com.estimote.proximity_sdk.proximity.ProximityObserver;
import com.estimote.proximity_sdk.proximity.ProximityObserverBuilder;
import com.estimote.proximity_sdk.proximity.ProximityZone;
import com.ubidots.ApiClient;
import com.ubidots.Variable;
import java.util.ArrayList;
import java.util.List;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
public class MainActivity extends AppCompatActivity {
private ProximityObserver proximityObserver;
private int send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EstimoteCloudCredentials cloudCredentials =
new EstimoteCloudCredentials("tan-kok-hui-s-proximity-fo-07q", "d18623351c273ce3e09ffcc1f6201861");
// 2. Create the Proximity Observer
this.proximityObserver =
new ProximityObserverBuilder(getApplicationContext(), cloudCredentials)
.withOnErrorAction(new Function1<Throwable, Unit>() {
#Override
public Unit invoke(Throwable throwable) {
Log.e("app", "proximity observer error: " + throwable);
return null;
}
})
.withLowLatencyPowerMode()
.build();
// add this below:
ProximityZone zone = this.proximityObserver.zoneBuilder()
.forTag("desks")
.inNearRange()
.withOnEnterAction(new Function1<ProximityContext, Unit>() {
#Override
public Unit invoke(ProximityContext context) {
String deskOwner = context.getAttachments().get("desk-owner");
Log.d("app", "Welcome to " + deskOwner + "'s desk");
return null;
}
})
.withOnExitAction(new Function1<ProximityContext, Unit>() {
#Override
public Unit invoke(ProximityContext context) {
return null;
}
})
.withOnChangeAction(new Function1<List<? extends ProximityContext>, Unit>() {
#Override
public Unit invoke(List<? extends ProximityContext> contexts) {
List<String> deskOwners = new ArrayList<>();
for (ProximityContext context : contexts) {
deskOwners.add(context.getAttachments().get("desk-owner"));
}
for (int i = 0; i < deskOwners.size(); i++) {
if (deskOwners.get(i).contains("Peter")) {
send = 1;
Toast.makeText(MainActivity.this, "Alert:Unauthorized Zone", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "Sending information to ubidots..........", Toast.LENGTH_LONG).show();
} else if (deskOwners.get(i).contains("Alex")) {
send = 0;
Toast.makeText(MainActivity.this, "Device has entered this range", Toast.LENGTH_SHORT).show();
}
else if (deskOwners.get(i).contains("Paul"))
{
}
}
Log.d("app", "In range of desks: " + deskOwners);
return null;
}
})
.create();
this.proximityObserver.addProximityZone(zone);
ProximityZone innerZone = this.proximityObserver.zoneBuilder()
.forTag("treasure")
.inCustomRange(3.0)
.create();
ProximityZone outerZone = this.proximityObserver.zoneBuilder()
.forTag("treasure")
.inCustomRange(9.0)
.create();
RequirementsWizardFactory
.createEstimoteRequirementsWizard()
.fulfillRequirements(MainActivity.this,
// onRequirementsFulfilled
new Function0<Unit>() {
#Override
public Unit invoke() {
Log.d("app", "requirements fulfilled");
proximityObserver.start();
return null;
}
},
// onRequirementsMissing
new Function1<List<? extends Requirement>, Unit>() {
#Override
public Unit invoke(List<? extends Requirement> requirements) {
Log.e("app", "requirements missing: " + requirements);
return null;
}
},
// onError
new Function1<Throwable, Unit>() {
#Override
public Unit invoke(Throwable throwable) {
Log.e("app", "requirements error: " + throwable);
return null;
}
});
}
private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (send == 1 || send == 0) {
new ApiUbidots().execute(send);
}
}
};
#Override
protected void onStart() {
super.onStart();
registerReceiver(mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
// Stop the BroadcastReceiver
#Override
protected void onStop() {
unregisterReceiver(mBatteryReceiver);
super.onStop();
}
// In Charge of sending variable to ubidots
public class ApiUbidots extends AsyncTask<Integer, Void, Void> {
private final String API_KEY = "A1E-0109ebb46b4990a4ed82f74d2912a9e6b481";
private final String VARIABLE_ID = "5b62ab7ac03f97418ba1c28e";
#Override
protected Void doInBackground(Integer... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable batteryLevel = apiClient.getVariable(VARIABLE_ID);
batteryLevel.saveValue(params[0]);
return null;
}
}
}
The problem is i am able to sending the data to the ubidots however i want to make it so that only if the condition has met, it will then send to the cloud. Other than that, it would not have send any data to the cloud.
package kr.phpdev.call;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.PhoneNumberUtils;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PhoneStateReceiver extends BroadcastReceiver {
static String mLastState;
static final String TAG = "Call Manager";
final OkHttpClient client = new OkHttpClient();
#Override
public void onReceive(Context context, Intent intent) {
CallReceivedChk(context, intent);
}
private void CallReceivedChk(Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String mState = String.valueOf(state);
if (mState.equals(mLastState)) { // 두번 호출되는 문제 해결 목적
return;
} else {
mLastState = mState;
}
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "CALL_IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "CALL_OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "CALL_RINGING >>> " + PhoneNumberUtils.formatNumber(incomingNumber));
RequestBody formBody = new FormBody.Builder()
.add("pn", PhoneNumberUtils.formatNumber(incomingNumber))
.build();
final Request request = new Request.Builder()
.url("http://phpdev.kr/cm/logsend.php")
.post(formBody)
.build();
AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
return null;
}
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != "FAILED") {
Log.d(TAG, s);
Toast.makeText(getApplicationContext(), "토스트메시지입니다.", Toast.LENGTH_SHORT).show();
}
}
};
asyncTask.execute();
break;
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
}
how can i get toast message?
You need to do that on onPostExecute since it is running on the UI thread. And also in Java string comparison is like s.equals("Failed"):
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!s.equals("FAILED")) {
Log.d(TAG, s);
Toast.makeText(context, "토스트메시지입니다.", Toast.LENGTH_SHORT).show();
}
}
Use Toast.makeText(context, "토스트메시지입니다.",Toast.LENGTH_SHORT).show();`
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != "FAILED") {
Log.d(TAG, s);
Toast.makeText(context, "토스트메시지입니다.", Toast.LENGTH_SHORT).show();
}
}
Error:(103, 68) error: local variable context is accessed from within inner class; needs to be declared final. You just need using "context" instead of "getApplicationContext()".
I am implementing socket messaging app using nodejs server ,html and android client. So that, i have implemented the following ways,
Step 1: Create the server with the following code which works fine.
const express = require('express');
const app = express();
const server = app.listen(3000,console.log("Socket.io Hello Wolrd server started!"));
const io = require('socket.io')(server);
io.on('connection', (socket) => {
//console.log("Client connected!");
socket.on('chat_sample_test', (msg) => {
console.log(msg.id);
console.log(msg.message);
socket.emit(msg.id, msg.message);
})
});
Step 2: I have created HTML client app with the following code and it is connected with server and works perfectly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var socket = io("http://192.168.1.138:3000");
socket.on("computer", function(msg) {
document.getElementById('server').innerHTML = msg;
});
$(document).ready(function(){
$("#btnSend").click(function(){
sendMsg();
});
$('#inptBox1').keypress(function (e) {
if (e.which == 13) {
sendMsg();
return false; //<---- Add this line
}
});
});
function sendMsg(){
var message=$("#inptBox1").val();
var messageObj={};
messageObj.id="mobile";
messageObj.message=message;
socket.emit('chat_sample_test', messageObj);
}
</script>
<p id="server" ></p>
<p id="client"></p>
<input type="text" id="inptBox1" placeholder="Enter msg">
<button id="btnSend">Send</button>
</body>
</html>
Step 3: I have implemented Android client with the following code and it's also connected with server works fine.
Custom Application class:
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.reconnection = false;
mSocket = IO.socket("http://192.168.1.138:3000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
MainActivity Class:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import io.socket.client.Ack;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText messageBox;
Button sendButton;
ListView chatroom;
ChatAdapter chatAdapter;
List<ChatModel> listItems = new ArrayList<>();
private Socket mSocket;
boolean isConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChatApplication app = (ChatApplication) getApplication();
mSocket = app.getSocket();
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, onConnectError);
mSocket.on("mobile",onMessageReceive);
mSocket.connect();
init();
}
void init() {
chatroom = (ListView) findViewById(R.id.chatroom);
sendButton = (Button) findViewById(R.id.sendButton);
messageBox = (EditText) findViewById(R.id.messageBox);
sendButton.setOnClickListener(this);
}
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isConnected) {
Toast.makeText(getApplicationContext(),
"Connected", Toast.LENGTH_LONG).show();
isConnected = true;
}
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
isConnected = false;
Toast.makeText(getApplicationContext(),
"Disconnected", Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Connection Error", Toast.LENGTH_LONG).show();
mSocket.connect();
}
});
}
};
Emitter.Listener onMessageReceive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (args.length > 0) {
JSONObject data = (JSONObject) args[0];
String username="";
String message="";
try {
username = data.getString("username");
message = data.getString("message");
Log.e("RECEIVE",username.concat(" "+message));
setAdapter(username, message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
};
void setAdapter(String name, String message) {
ChatModel chatModel = new ChatModel();
chatModel.setUserName(name);
chatModel.setMessage(message);
listItems.add(chatModel);
if (chatAdapter == null) {
chatAdapter = new ChatAdapter(this, listItems);
chatroom.setAdapter(chatAdapter);
} else {
chatAdapter.notifyDataSetChanged();
}
chatroom.setSelection(chatAdapter.getCount() - 1);
}
private void attemptSend() {
String message = messageBox.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
return;
}
messageBox.setText("");
try {
JSONObject obj = new JSONObject();
obj.put("username", "Hassan");
obj.put("message", message);
obj.put("id", "computer");
mSocket.emit("chat_sample_test", obj, new Ack() {
#Override
public void call(Object... args) {
Toast.makeText(MainActivity.this,"Message received by device",Toast.LENGTH_SHORT).show();
}
});
setAdapter("me", message);
Log.e("SEND",message);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sendButton:
attemptSend();
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off(Socket.EVENT_CONNECT, onConnect);
mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("mobile", onMessageReceive);
}
}
My logic here is, from the html application, i will send the message to mobile and vice versa.First, I have connected with the chat_sample_test room. when i tried to send the message using html application, the server prints the message based on the console i have added in nodejs server. but the mobile not receiving the message. the same happening in mobile end.No error found.
NOTE:
when i try to send the message to mobile , i have added the id as mobile (mobile need to receive the message), where as in mobile i have added id as computer(Computer need to receive the message)
Helps will be appreciated.
Just now i found the answer. thank you guys who are all try to solve the issue.
const express = require('express');
const app = express();
const server = app.listen(3000,console.log("Socket.io Hello Wolrd server started!"));
const io = require('socket.io')(server);
io.on('connection', (socket) => {
//console.log("Client connected!");
socket.on('chat_sample_test', (msg) => {
console.log(msg.id);
console.log(msg.message);
socket.broadcast.emit(msg.id, msg.message);//here added broadcast obj.So now working fine.
})
});
I am trying out the WebSockets with Fallbacks transports for Android, Node.js and Atmosphere example. I get an the following error:
/home/mofa/NetBeansProjects/App/src/com/jullio/advisor/wAsyncChat.java:87: error: cannot access JsonParseException
return mapper.readValue(data, Message.class);
class file for org.codehaus.jackson.JsonParseException not found
/home/mofa/NetBeansProjects/App/src/com/jullio/advisor/wAsyncChat.java:68: error: cannot access ObjectCodec
return mapper.writeValueAsString(data);
class file for org.codehaus.jackson.ObjectCodec not found
Here is the androidchat code:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.atmosphere.wasync.ClientFactory;
import org.atmosphere.wasync.Decoder;
import org.atmosphere.wasync.Encoder;
import org.atmosphere.wasync.Event;
import org.atmosphere.wasync.Function;
import org.atmosphere.wasync.Request;
import org.atmosphere.wasync.RequestBuilder;
import org.atmosphere.wasync.impl.AtmosphereClient;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.Date;
public class wAsyncChat extends Activity {
private Button bt;
private TextView tv;
private String serverIpAddress = "http://10.0.2.2:8080";
private final static ObjectMapper mapper = new ObjectMapper();
private final Handler uiHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
AtmosphereClient client = ClientFactory.getDefault().newClient(AtmosphereClient.class);
RequestBuilder request = client.newRequestBuilder()
.method(Request.METHOD.GET)
.uri(serverIpAddress + "/chat")
.trackMessageLength(true)
.encoder(new Encoder<Message, String>() {
#Override
public String encode(Message data) {
try {
return mapper.writeValueAsString(data);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
})
.decoder(new Decoder<String, Message>() {
#Override
public Message decode(Event type, String data) {
data = data.trim();
// Padding
if (data.length() == 0) {
return null;
}
if (type.equals(Event.MESSAGE)) {
try {
return mapper.readValue(data, Message.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
})
.transport(Request.TRANSPORT.WEBSOCKET);
final org.atmosphere.wasync.Socket socket = client.create();
socket.on("message", new Function<Message>() {
#Override
public void on(final Message t) {
uiHandler.post(new Runnable() {
#Override
public void run() {
Date d = new Date(t.getTime());
tv.append("Author " + t.getAuthor() + "# " + d.getHours() + ":" + d.getMinutes() + ": " + t.getMessage() + "\n");
}
});
}
}).on(new Function<Throwable>() {
#Override
public void on(Throwable t) {
tv.setText("ERROR 3: " + t.getMessage());
t.printStackTrace();
}
}).open(request.build());
bt.setOnClickListener(new OnClickListener() {
String name = null;
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
if (name == null) {
name = str;
}
socket.fire(new Message(name, str));
et.setText("");
Log.d("Client", "Client sent message");
} catch (Throwable e) {
tv.setText("ERROR 3: " + e.getMessage());
e.printStackTrace();
}
}
});
} catch (Throwable e) {
tv.setText("Unable to connect: " + e.getMessage());
e.printStackTrace();
}
}
}
I have the library for nodeserver connection. You can use it from git
SocketIO socketio = new SocketIO() {
#Override
public void onConnect() {
}
#Override
public void onDisconnect() {
}
#Override
public void onMessage(String message) {
Log.d("===Server Answer====",message);
}
};
socketio.Connect("192.168.0.1", 9000);
after onConnect() send the message:
socketio.send("Your message to socket");
it work with latest socketIO, and use RFC 6455 websocket protocol