Signalr with android client - android

Hi I'm new to Signalr and I want to develop android native client application for communicate with signalr server. So I follow "whathecode" article and still i'm not able to connect to server. Anyone can give me some sample project or example.Its big help for me. Thank you.
public void connect(){
HubConnection con = new HubConnection(Uri.parse("http://10.0.2.2:3227/").toString());
HubProxy hub = con.createHubProxy("MyHub1");
con.start();
try {
hub.invoke( "Send", "user", "Hello world!" ).get();
} catch (InterruptedException e) {
// Handle ...
} catch (ExecutionException e) {
// Handle ...
}
}

I face same issue like you but it resolved by adding 3227 part to allow all connection from it in my windows firewall settings .
I also suggest instead of creating localhost use some ip and create SignalR server, after that it should work fine.

private void createConnections() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String host = "http://192.168.0.63/SignalRServerApp/signalr";
final HubConnection connection = new HubConnection(host, false);
final HubProxy hp = connection.createHubProxy("MyHubController");
Toast.makeText(getActivity(), SampleWork.getStringData(), Toast.LENGTH_LONG).show();
System.out.println(SampleWork.getStringData());
SignalRFuture<Void> awaitConnection = connection.start();
try {
EditText text = (EditText) getActivity()
.findViewById(R.id.text);
String data = text.getText().toString();
awaitConnection.get();
try {
hp.invoke("ReceiveData", data);
} catch (Exception e) {
System.out.println("Error");
}
//Calling a server method named "Acknowledge"
hp.on("Acknowledge", new SubscriptionHandler1<String>() {
#Override
public void run(final String p1) {
//Here u gets the response from server
}
}, String.class);
System.out.println("Test");
} catch (Exception e) {
e.printStackTrace();
}
}`enter code here`

Related

Observe Socket-IO Messages

I am implementing a chat feature in my app using nkzawa sockets library. I have sent message to server using sockets and an endpoint (url string).
I have heard talk about RxJava and RxAndroid being the best way to observer data streams.
Observable.from(MyEndPoint).subscribe()
But I am having trouble passing a url parameter to observable.
Is it possible to create an observable to listen on my server's endpoint for new and existing messages. Please how do you go about retrieving socket messages in this way or another way, Thanks.
Edited as suggested:
Here's the code snippet I tried without Rx but not working:
private com.github.nkzawa.socketio.client.Socket mSocket;
{
try {
mSocket = IO.socket(Constants.PUBLIC_CHAT_ENDPOINT);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
Socket initialized like above and connected here:
mSocket.connect();
I am trying to get messages as demoed in the library docs but not working.
mSocket.on(Constants.SOCKET_GET_MESSAGE_EVENT, new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject jsonObject = (JSONObject) args[0];
JSONObject dataObject = jsonObject.getJSONObject("data");
String type = dataObject.getString("type");
Log.d(TAG, "Message is of type:\t" + type);
JSONObject contentObject = dataObject.getJSONObject("content");
String roomId = contentObject.getString("roomid");
String userId = contentObject.getString("userId");
String message = contentObject.getString("message");
Log.d(TAG, "Get Message is:\t" + message);
Log.d(TAG, "roomId:\t" + roomId);
Log.d(TAG, "Get userId is:\t" + userId);
TingTingUser otherUsers = new TingTingUser(userId, "Abhiram Labhani", "Unknown");
HomeMessage othersHomeMessages = new HomeMessage(message, otherUsers, System.currentTimeMillis());
List<HomeMessage> othersList = new ArrayList<>();
othersList.add(othersHomeMessages);
Log.d(TAG, "Other Messages size is:\t " + othersList.size());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
I want to implement the above code using RxJava but have no idea how to observe data from a dynamic, constantly updating endpoint as most of the docs and articles only use pre-defined data. Thanks.

SignalR Android client not Hitting OnConnected method in Server

I have the following TestHub class in my server.
public class TestHub:Hub {
public override Task OnConnected() {
//do some work here
return base.OnConnected();
}
}
and my android client uses the following code to start negotiating with server.
//set serverUrl, device_id, logger, serverHub
Platform.loadPlatformComponent(new AndroidPlatformComponent());
HubConnection connection = new HubConnection(serverUrl, "device_id="+device_id, false, logger);
HubProxy proxy = connection.createHubProxy(serverHub);
proxy.subscribe(this);
proxy.on("test", new SubscriptionHandler1<String>() {
#Override
public void run(String x) {
System.out.println(x);
}
}, String.class);
ClientTransport clientTransport = new ServerSentEventsTransport(connection.getLogger());
SignalRFuture<Void> signalRFuture = connection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
I'm trying to do some work in server OnConnected() method but it won't hit. i have signalr connection successfully but i want to do some stuff in OnConnected() method. what should i do?

Not able to send message using smack Android

i am trying to send message to client but always getting this exception: org.jivesoftware.smack.SmackException$NotConnectedException: Client is not, or no longer, connected.
Following are my code to send message:
ChatManager chatMngr = ChatManager.getInstanceFor(connection);
Chat chat = chatMngr.createChat(toName + "#stag-api.artistaloud.com", FrgChatRoom.this);
try {
chat.sendMessage(txtChatMsg.getText().toString().trim());
} catch (Exception e) {
e.printStackTrace();
}
When i am relogin before send the message. its working fine...please reply..
this exception occurs while you are not connected with Xmpp server.
first insure that are you connect with server or not?.and for get connected with server with asmack libs use this code:
private class ConnectToXmpp extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ConnectionConfiguration config = new ConnectionConfiguration( server_host, SERVER_PORT);
XMPPConnection m_connection = new XMPPConnection(config);
try {
SASLAuthentication.supportSASLMechanism("PLAIN");
config.setSASLAuthenticationEnabled(true);
m_connection.connect();
Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
and now you can execute this as new ConnectToXmpp().execute();
and for sending message you have to create chat like:
ChatManager chatmanager = ChatManager.getInstanceFor(connection);
Chat newChat = chatmanager.createChat("jsmith#jivesoftware.com", new MessageListener() {
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
try {
newChat.sendMessage("Howdy!");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
and Chat.sendMessage(String) method is a convenience method that creates a Message object, sets the body using the String parameter, then sends the message.
and then use this code sniipet for send message:
Message newMessage = new Message();
newMessage.setBody("Howdy!");
message.setProperty("favoriteColor", "red");
newChat.sendMessage(newMessage);
and for more information see this link.

Getting bad request 400 error using asmack in android

I am trying to register a new user using my XMPP client using asmack library in Android on ejabberd server. The problem is that I am getting following error & the user is not being created on the server:
bad-request(400)
at org.jivesoftware.smack.AccountManager.createAccount(AccountManager.java:243)
at in.ui.MainActivity$1$1$1.run(MainActivity.java:316)
at java.lang.Thread.run(Thread.java:841)
Following is the code:
_xmppUsername = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_CLIENT_ID);
_xmppPassword = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_CLIENT_PASSWORD);
_xmppHost = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_HOST);
try {
_xmppPortNo = Integer.parseInt (XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_PORT));
} catch (Exception e) {
e.printStackTrace ();
Log.e (TAG, e.getMessage ());
}
_xmppServiceName = XMPPConfig.getStringUserInfoValue (XMPPConfig.XMPP_SERVICE_NAME);
ConnectionConfiguration conConfig = new ConnectionConfiguration (_xmppHost, _xmppPortNo, _xmppServiceName);
_xmppConnection = new XMPPConnection (conConfig);
if (!_xmppConnection.isAuthenticated ()) {
login ();
}
/*
* If connection has not been established or had been established &
* broken again then login
*/
#Override
public void onShow (final DialogInterface dialog) {
Button positiveButton = _dlgRegistration.getButton (DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
// Creating registration thread
new Thread (new Runnable () {
#Override
public void run () {
String clientID = null;
String password = null;
clientID = "user" + XMPP_SERVICE_NAME;
try {
// Getting hash password from UUID
password = "password";
Log.i (TAG, clientID + password);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace ();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace ();
}
}
AccountManager manager = _xmppConnection.getAccountManager ();
try {
// Creating account on the server
manager.createAccount (clientID, password, attr);
}
} catch (XMPPException e) {
e.printStackTrace ();
}
}
}).start ();
}
});
The problem was this line clientID = "user" + XMPP_SERVICE_NAME; where I shouldn't have been appending Domain or Service Name after "user".

Connecting to MySQL from Android with JDBC

I used the following code to connect MySQL in localhost from Android. It only displays the actions given in catch section . I do not know whether it is a connection problem or not.
package com.test1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Test1Activity extends Activity {
/** Called when the activity is first created. */
String str="new";
static ResultSet rs;
static PreparedStatement st;
static Connection con;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv=(TextView)findViewById(R.id.user);
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://10.0.2.2:8080/example","root","");
st=con.prepareStatement("select * from country where id=1");
rs=st.executeQuery();
while(rs.next())
{
str=rs.getString(2);
}
tv.setText(str);
setContentView(tv);
}
catch(Exception e)
{
tv.setText(str);
}
}
}
When this code executes it displays "new" in the avd.
java.lang.management.ManagementFactory.getThreadMXBean, referenced from method com.mysql.jdbc.MysqlIO.appendDeadlockStatusInformation
Could not find class 'javax.naming.StringRefAddr', referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.storeTo
Could not find method javax.naming.Reference.get, referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.initializeFrom
Can anyone suggest some solution? And thanks in advance
You can't access a MySQL DB from Android natively. EDIT: Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver
See
http://www.helloandroid.com/tutorials/connecting-mysql-database
http://www.basic4ppc.com/forum/basic4android-getting-started-tutorials/8339-connect-android-mysql-database-tutorial.html
Android cannot connect directly to the database server. Therefore we
need to create a simple web service that will pass the requests to the
database and will return the response.
http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html
For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.
this code runs permanently!!! created by diko(Turkey)
public void mysql() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
thrd1 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
if (con == null) {
try {
con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
if ((thrd2 != null) && (!thrd2.isAlive()))
thrd2.start();
}
}
}
});
if ((thrd1 != null) && (!thrd1.isAlive())) thrd1.start();
thrd2 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
if (con != null) {
try {
// con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
Statement st = con.createStatement();
String ali = "'fff'";
st.execute("INSERT INTO deneme (name) VALUES(" + ali + ")");
// ResultSet rs = st.executeQuery("select * from deneme");
// ResultSetMetaData rsmd = rs.getMetaData();
// String result = new String();
// while (rs.next()) {
// result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
// result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
// }
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
}
If u need to connect your application to a server you can do it through PHP/MySQL and JSON http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ .Mysql Connection code should be in AsynTask class. Dont run it in Main Thread.
Do you want to keep your database on mobile? Use sqlite instead of mysql.
If the idea is to keep database on server and access from mobile. Use a webservice to fetch/ modify data.
An other approach is to use a Virtual JDBC Driver that uses a three-tier architecture: your JDBC code is sent through HTTP to a remote Servlet that filters the JDBC code (configuration & security) before passing it to the MySql JDBC Driver. The result is sent you back through HTTP. There are some free software that use this technique. Just Google "Android JDBC Driver over HTTP".
try changing in the gradle file the targetSdkVersion to 8
targetSdkVersion 8
public void testDB() {
TextView tv = (TextView) this.findViewById(R.id.tv_data);
try {
Class.forName("com.mysql.jdbc.Driver");
// perfect
// localhost
/*
* Connection con = DriverManager .getConnection(
* "jdbc:mysql://192.168.1.5:3306/databasename?user=root&password=123"
* );
*/
// online testing
Connection con = DriverManager
.getConnection("jdbc:mysql://173.5.128.104:3306/vokyak_heyou?user=viowryk_hiweser&password=123");
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from tablename ");
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";
}
tv.setText(result);
} catch (Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
}

Categories

Resources