android - Autobahn Websocket Connection - android

I am working on Autobahn Web socket communication. There is a carousel view in my application, and there are four images. When users click on of the images, then connects to server with websocket and send message. But the problem is that when I select the images, it connects to server correctly, but client(android device) connects to the websocket every single time when the message is sent.
Here is my code..
if (pos == 0) {
product_photo.setImageResource(R.drawable.myoffers_0);
product_photo.setOnClickListener(new ImageButton.OnClickListener(){
public void onClick(View v){
String id = "Product0";
Log.d(TAG, "Current product is : " + id);
A.sendMessage(id);
}
});
}
Websocket.class
public class WebSocket_Connector extends Activity{
private static final String TAG = "ECHOCLIENT";
private static final String TAG1 = "My app";
public final WebSocketConnection mConnection = new WebSocketConnection();
private String tmpString = "";
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
mConnection.sendTextMessage(tmpString);
tmpString = "";
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
public void sendMessage(String message) {
if (mConnection.isConnected()) {
Log.d(TAG1, "Messeage is sent : " + message);
mConnection.sendTextMessage(message);
}
else {
tmpString = message;
connect("ws://xxx.xxx.x.xxx:xxxx");
}
}
}
It doens't go to 'if (mConnection.isConnected())' here..always goes to else.

Related

samsung device not connect to other device using web socket

Now i'm try to connect with other device using samsung S6 Lite. Here i have a problem while connecting to the other device it's trying to connect and after few second it's OnClose method will call in my web socket listener.
I have tried on same thing in Samsung S7, Samsung S5 and emulator it's working fine. Only i got the connection issue in Samsung S6(OS: Android 11).
Node.js
const http = require('http');
const WebSocketServer = require('websocket').server;
const server = http.createServer();
server.listen(8080);
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
const connection = request.accept(null, request.origin);
console.log('Server Connected')
connection.on('message', function(message) {
console.log('Received Message:', message.utf8Data);
//connection.sendUTF('Hi this is WebSocket server!');
connection.sendUTF('Socket server conne');
});
connection.on('close', function(reasonCode, description) {
console.log('Client has disconnected.',description.utf8Data);
});
connection.on('error', function(error){
console.log('Client has error',error.utf8Data);
});
connection.on('frame', function(frame){
console.log('Client has frame');
});
});
wsServer.on('connect',function(connection){
console.log('Server connection status: ');
connection.on('message', function(message){
console.log('Server Received Message:', message.utf8Data);
});
});
Android Connection Code:
public void test() {
try {
URI uri;
try {
uri = new URI("ws://localhost:8080/test");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
String myAndroidDeviceId = Settings.Secure.getString(getApplicationContext().getContentResolver(), ANDROID_ID);
Map<String, String> stringStringMap = new HashMap<>();
stringStringMap.put("device", "device," + myAndroidDeviceId);
String temp[] = {"device:device"};
cc = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
String str = android.os.Build.MODEL;
String record = "Device Name : " + str;
// cc.send(String.valueOf(record));
cc.send(record);
System.out.println("Address" + cc.getRemoteSocketAddress());
Log.i("Websocket", "Opened");
System.out.println("SocketIPAddress--->Opened--->");
}
#Override
public void onMessage(String s) {
final String message = s;
System.out.println(message);
System.out.println("SocketIPAddress--->onMessage--->" + s);
updateUI(message);
}
#Override
public void onClose(int i, String s, boolean b) {
// Log.i("Websocket", "Closed " + s);
System.out.println("SocketIPAddress--->onClose--->" + s);
//updateUI("Disconnected");
}
#Override
public void onError(final Exception e) {
System.out.println("SocketIPAddress--->onError--->" + e.getMessage());
}
};
cc.connect();
} catch (Exception ex) {
Log.i("ErrorMsg", ex.getMessage());
}
}
Any one please help to fix this issue. Thanks

Smack XMPP connection not connecting over 4G network

I am using the latest Smack library 4.3.1. The XMPP connection is working fine
with WiFi but it's not working with 4G network.
Here is my code for creating a connection with XMPP.
configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(this.userName, this.password);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setServiceName(Constants.HOST);
configBuilder.setPort(Constants.PORT);
configBuilder.setHost(Constants.HOST);
configBuilder.setDebuggerEnabled(Isdebugmode);
configBuilder.setResource(PDCustomer.getResource());
configBuilder.setSendPresence(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.setPacketReplyTimeout(30000);
connection.addConnectionListener(XmppConnection.this);
connection.addAsyncStanzaListener(XmppConnection.this, null);
try {
connection.connect();
connection.login(userName, password);
} catch (IOException e) {
printlog("CONNECT IO EXCEPTION:" + e.getMessage());
} catch (SmackException e) {
printlog("CONNECT SMACK EXCEPTION:" + e.getMessage());
} catch (XMPPException e) {
printlog("CONNECT XMPP EXCEPTION:" + e.getMessage());
}
I have tested below code in 4G network
Create new class of XMPPConnection
public class XMPPConnection implements ConnectionListener, ChatManagerListener, RosterListener, ChatMessageListener, PingFailedListener {
private static final String TAG = "XMPPConnection";
public static final String HOST = "XX.XX.XXX.XX"; //Replace this value
public static final int PORT = 5222;
public static final String SERVICE = "XX.XX.XXX.XX"; //Replace this value
public static String USERNAME = ""; // Replace this value
public static String PASSWORD = ""; //Replace this value
public static String TEST_JID = "android_dummy"; // Only for testing purpose
private static XMPPConnection mInstance = new XMPPConnection();
private AbstractXMPPConnection mConnection;
private ChatManager mChatmanager;
private Chat mChat;
private Context mContext;
private String mUserName = "";
private String mPassword = "";
public XMPPConnection() {
}
public static XMPPConnection getInstance() {
return mInstance;
}
//Initialize
public void init(String userId, String pwd, Context context) throws SmackException.NotConnectedException {
Log.i("XMPP", "Initializing!");
this.mUserName = userId;
this.mPassword = pwd;
this.mContext = context;
if (userId.contains("#")) {
this.mUserName = userId.split("#")[0];
Log.i("UserId", this.mUserName);
}
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(mUserName, mPassword);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setServiceName(SERVICE);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
configBuilder.setResource("");
//configBuilder.setDebuggerEnabled(true);
mConnection = new XMPPTCPConnection(configBuilder.build());
PingManager pingManager = PingManager.getInstanceFor(mConnection);
pingManager.setPingInterval(300); // 2.5 min
pingManager.registerPingFailedListener(this);
mChatmanager.getInstanceFor(mConnection).addChatListener(this);
ReconnectionManager.getInstanceFor(mConnection).enableAutomaticReconnection();
mConnection.addConnectionListener(this);
connectConnection(context);
}
public void connectConnection(final Context context) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
mConnection.connect();
if (mConnection != null) {
Log.i(TAG, "doInBackground: ServerStatus:Connected= " + mConnection.isConnected());
login(context);
}
} catch (IOException e) {
Log.i(TAG, "doInBackground : ServerStatus : IOException = " + e.getMessage());
} catch (SmackException e) {
Log.i(TAG, "doInBackground : ServerStatus : SmackException = " + e.getMessage());
} catch (XMPPException e) {
Log.i(TAG, "doInBackground : ServerStatus : XMPPException = " + e.getMessage());
}
return null;
}
};
connectionThread.execute();
}
public void login(Context context) {
try {
Log.i(TAG, "login: USERNAME:" + mUserName + " PASSWORD:" + mPassword);
mConnection.login(mUserName, mPassword);
if (mConnection.isAuthenticated()) {
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
sendMessage("", TEST_JID, "", "", "", "android_dummy", "android", "android", context);
}
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
Log.i(TAG, "Login : Exception = " + e.getMessage());
}
}
public void sendMessage(String message, String to, String from, String dattingId, String deviceToken, String senderName, String senderOSName, String opponentOSName, Context context) {
this.mContext = context;
if (mConnection.isConnected() == true) {
Log.i(TAG, "sendMsg: Sending Message...");
// Assume we've created an XMPPConnection name "connection".
mChatmanager = ChatManager.getInstanceFor(mConnection);
mChat = mChatmanager.createChat("" + to, this);
// Original code
try {
Message msg = new Message();
// Set message
msg.setBody(message);
msg.setType(Message.Type.chat);
msg.setTo("" + to);
msg.setFrom("" + from);
Log.i(TAG, "Message to send : " + msg.toXML());
mChat.sendMessage(msg);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "sendMsg : Unable to send Message.");
}
}
// Disconnect Function
public void disconnectConnection() {
new Thread(new Runnable() {
#Override
public void run() {
if (mConnection != null && mConnection.isConnected())
mConnection.disconnect();
mConnection = null;
}
}).start();
}
#Override
public void processMessage(Chat chat, Message message) {
if (mConnection.isConnected() && mConnection != null) {
Log.i(TAG, "Message " + message);
}
}
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
Log.i(TAG, "chatCreated()");
chat.addMessageListener(this);
}
#Override
public void connected(org.jivesoftware.smack.XMPPConnection connection) {
Log.i(TAG, "Listener connected = " + connection.getUser());
}
#Override
public void authenticated(org.jivesoftware.smack.XMPPConnection connection, boolean resumed) {
Log.i(TAG, "Listener authenticated = " + connection.getUser());
Log.i(TAG, "Listener authenticated = resumed : " + resumed);
}
#Override
public void connectionClosed() {
Log.i(TAG, "Listener connectionClosed");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.i(TAG, "Listener connectionClosedOnError = " + e.getMessage());
}
#Override
public void reconnectionSuccessful() {
Log.i(TAG, "Listener reconnectionSuccessful");
if (mContext != null) {
sendMessage("", TEST_JID, "", "", "", "android_dummy", "android", "android", mContext);
}
}
#Override
public void reconnectingIn(int seconds) {
Log.i(TAG, "Listener reconnectingIn = " + seconds);
}
#Override
public void reconnectionFailed(Exception e) {
Log.i(TAG, "Listener reconnectionFailed = " + e.getMessage());
}
#Override
public void pingFailed() {
Log.i(TAG, "Listener pingFailed");
}
#Override
public void entriesAdded(Collection<String> addresses) {
}
#Override
public void entriesUpdated(Collection<String> addresses) {
}
#Override
public void entriesDeleted(Collection<String> addresses) {
}
#Override
public void presenceChanged(Presence presence) {
Log.i(TAG, "presenceChanged: " + presence.getClass().toString());
}
}
Now call init() method like,
// Check XMPP connection
try {
XMPPConnection.getInstance().init(USER_JABBERID, USER_JABBER_PASSWORD, HomeActivity.this);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}

Paho Android client drops connection when a message is shown

I am trying to use the basic Eclipse Paho MQTT client version 1.1.0 to connect to a CloudAMQP RabbitMQ instance, subscribe to a topic, and receive messages (which I send from the web admin console).
It works well if the application sends all message payloads to the Log output.
If the application adds the message to a TextView, the message appears, but the connection is dropped immediately and no more message are received.
The full project is available at GitHub. A simple example is below.
There is a service-based MQTT Paho client, but I thought that for very simple applications the basic client should be able to receive and show messages in the Android app UI.
...
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MainActivity extends AppCompatActivity implements MqttCallback {
private static final String TAG = "main";
private Connection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
configureUI();
}
private Button buttonConnect;
private TextView messageWindow;
private void configureUI() {
buttonConnect = (Button) findViewById(R.id.buttonConnect);
messageWindow = (TextView) findViewById(R.id.messageWindow);
buttonConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = "***";
String d = "test";
String u = "***";
String p = "***";
if (connection != null && connection.isConnected()) {
connection.disconnect();
connection = null;
messageWindow.setText(String.format("Disconnected from server %s",
new Object[]{s}));
return;
}
messageWindow.setText(String.format("Connecting to server %s as user %s",
new Object[]{s, u}));
connection = new Connection(MainActivity.this, MainActivity.this, s, u, p);
connection.connect();
if (connection.isConnected()) {
messageWindow.append("\n\n");
messageWindow.append(String.format("Connected, listening for messages from topic %s",
new Object[]{d}));
connection.subscribe(d);
}
}
});
}
#Override
public void connectionLost(Throwable cause) {
Log.e(TAG, "connectionLost" + cause.getMessage());
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
String msg = new String(message.getPayload());
Log.i(TAG, "Message Arrived: " + msg);
// messageWindow.append(msg);
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.i(TAG, "Delivery Complete!");
}
class Connection {
private static final String TAG = "conn";
private static final String protocol = "tcp://";
private static final int port = 1883;
private static final int version = MqttConnectOptions.MQTT_VERSION_3_1_1;
private static final int keepAliveSeconds = 20 * 60;
private final Context context;
private MqttClient client;
private final String server;
private final String user;
private final String pass;
private final MqttConnectOptions options = new MqttConnectOptions();
public Connection(Context ctx, MqttCallback mqttCallback, String server, String user, String pass) {
this.context = ctx;
this.server = server;
this.user = user;
this.pass = pass;
MqttClientPersistence memPer = new MemoryPersistence();
try {
String url = protocol + server + ":" + port;
client = new MqttClient(url, MqttClient.generateClientId(), memPer);
client.setCallback(mqttCallback);
} catch (MqttException e) {
e.printStackTrace();
}
options.setUserName(user + ":" + user);
options.setPassword(pass.toCharArray());
options.setMqttVersion(version);
options.setKeepAliveInterval(keepAliveSeconds);
}
void connect() {
Log.i(TAG, "buttonConnect");
try {
client.connect(options);
} catch (MqttException ex) {
Log.e(TAG, "Connection attempt failed with reason code = " + ex.getReasonCode() + ":" + ex.getCause());
}
}
public boolean isConnected() {
return client.isConnected();
}
public void disconnect() {
try {
client.disconnect();
} catch (MqttException e) {
Log.e(TAG, "Disconnect failed with reason code = " + e.getReasonCode());
}
}
void subscribe(String dest) {
try {
client.subscribe(dest);
} catch (MqttException e) {
Log.e(TAG, "Subscribe failed with reason code = " + e.getReasonCode());
}
}
}
}
I would guess this is because you are trying to update the TextView from a none UI thread.
Try wrapping the messageWindow.append(msg); in a runOnUiThread call.
public void messageArrived(String topic, MqttMessage message) throws Exception {
String msg = new String(message.getPayload());
Log.i(TAG, "Message Arrived: " + msg);
runOnUiThread(new Runnable(){
public void run() {
messageWindow.append(msg);
}
});
}

Push Notification Certificate issue

I am developing Push notification from Stackmob, But notification not being sent to mobile.
When i see in the console then it shows query true , and token is also able to generate.
Is there any certificate issue for developing push Notification from Stackmob?
public class PushDemoActivity extends Activity {
public static String SENDER_ID = "552151775896";
private StackMobUser user;
private static final String TAG = PushDemoActivity.class.getCanonicalName();
private final StackMobCallback standardToastCallback = new StackMobCallback() {
#Override public void success(String responseBody) {
threadAgnosticToast(PushDemoActivity.this, "response: " + responseBody, Toast.LENGTH_SHORT);
Log.i(TAG, "request succeeded with " + responseBody);
}
#Override public void failure(StackMobException e) {
threadAgnosticToast(PushDemoActivity.this, "error: " + e.getMessage(), Toast.LENGTH_SHORT);
Log.i(TAG, "request had exception " + e.getMessage());
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StackMobAndroid.init(this.getApplicationContext(), StackMob.OAuthVersion.One, 0, "da444511-860e-4b84-ac31-164bb349bd8f", "47e302a3-dd88-4323-8d20-cafe9e6ed7a8");
// Register for GCM Push
try {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
registerForPush();
} else {
Log.v(TAG, "Already registered");
}
} catch(UnsupportedOperationException e) {
Log.w(TAG, "This device doesn't support gcm. Push will not work");
}
}
public void loginClick(View v) {
user.login(standardToastCallback);
}
public void createUserClick(View v) {
user = new User(getUsername(), getPassword());
user.save();
}
public void registerRegTokenClick(View w) {
try {
user.registerForPush(new StackMobPushToken(getRegistrationIDHolder().getID()), standardToastCallback);
}
catch( Exception e) {
threadAgnosticToast(PushDemoActivity.this, "no registration ID currently stored", Toast.LENGTH_SHORT);
}
}
public void sendPushClick(View w) {
final Map<String, String> payload = new HashMap<String, String>();
payload.put("payload", getPushPayload());
user.sendPush(payload, standardToastCallback);
}
public void getRegTokenClick(View w) {
try {
threadAgnosticToast(PushDemoActivity.this, getRegistrationIDHolder().getID(), Toast.LENGTH_SHORT);
}
catch(PushRegistrationIDHolder.NoStoredRegistrationIDException e) {
threadAgnosticToast(PushDemoActivity.this, "no registration ID currently stored", Toast.LENGTH_SHORT);
}
}
public void forceGetRegTokenClick(View w) {
registerForPush();
threadAgnosticToast(PushDemoActivity.this, "sent intent to get reg ID", Toast.LENGTH_SHORT);
}
private PushRegistrationIDHolder getRegistrationIDHolder() {
return new PushRegistrationIDHolder(PushDemoActivity.this);
}
private void registerForPush() {
GCMRegistrar.register(this, SENDER_ID);
}
private EditText getUsernameField() {
return (EditText)findViewById(R.id.username);
}
private EditText getPasswordField() {
return (EditText)findViewById(R.id.password);
}
private String getUsername() {
return getUsernameField().getText().toString();
}
private String getPassword() {
return getPasswordField().getText().toString();
}
private EditText getPushPayloadField() {
return (EditText)findViewById(R.id.token_username);
}
private String getPushPayload() {
return getPushPayloadField().getText().toString();
}
private void threadAgnosticToast(final Context ctx, final String txt, final int duration) {
runOnUiThread(new Runnable() {
#Override public void run() {
Toast.makeText(ctx, txt, duration).show();
}
});
}

Android - Autobahn web socket communication

I am working on Web socket communication with Autobahn library.
The problem I have is after connecting server, then message should be sent without connection again. But the message is sent with different connection that it connects to server every single time to send a message.
public class WebSocket_Connector extends Activity{
private static final String TAG = "ECHOCLIENT";
private static final String TAG1 = "My app";
public final WebSocketConnection mConnection = new WebSocketConnection();
private String tmpString = "";
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
mConnection.sendTextMessage(tmpString);
tmpString = "";
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
public void sendMessage(String message) {
if (mConnection.isConnected()) {
Log.d(TAG1, "Messeage is sent : " + message);
mConnection.sendTextMessage(message);
}
else {
tmpString = message;
connect("ws://192.168.3.100:7681");
}
}
}
This is the code I have, and...When you see "sendMessage" method, it always goes to 'else' not, if loop. Any suggestion 'experts' please..?
i don't know the package name you are dealing with for websocket. So first it has to be provided to get reliable answer to your question. But let say if it is something similar to :
https://code.google.com/p/weberknecht/source/browse/trunk/src/main/de/roderick/weberknecht/WebSocketConnection.java?r=2
note: i have not seen there isConnected() method but assume that it is added somewhere else.
you can see from source that onOpen() (line 88) is called before connected = true; on line (91). if this member var will be used as result of isConnected() then your code always will follow "else" part of the condition.
i would advice to dig into websocket api and its usage pattern further.

Categories

Resources