Not able to send message using smack Android - 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.

Related

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?

Android socket client not receiving from java server

My app is sending data to the java socket server but it is only displaying the first message it receives from the server and not the other messages.
The Server is multi threaded.
I have created two clients in java both are sending and receiving messages through the server but in android app I am having problem receiving data.
This is the complete code of the Android client.
public class MainActivity extends AppCompatActivity {
Socket client;
EditText writeMsg;
TextView displayMsg;
String userInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
writeMsg = (EditText) findViewById(R.id.editText1);
displayMsg = (TextView) findViewById(R.id.textView);
ReceiveMsg obj = new ReceiveMsg();
Thread tr = new Thread(obj);
tr.start();
}
// A button to send msg to server when clicked
public void sendBtn(View view){
userInput = writeMsg.getText().toString();
SendMessage object = new SendMessage();
object.execute();
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
client = new Socket("10.0.2.2", 4444);
PrintWriter output = new PrintWriter(client.getOutputStream(), true);
output.print(userInput);
output.flush();
output.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
class ReceiveMsg implements Runnable {
public void run() {
try {
client = new Socket("10.0.2.2", 4444);
BufferedReader in =
new BufferedReader(
new InputStreamReader(client.getInputStream()));
int i = 0;
while (i == 0) {
displayMsg.setText(in.readLine());
}
} catch (Exception e) {
}
}
}
}
I want the app to display the newly received message in the text-view and overwrite the existing message.
You create two client sockets. One for sending and one for receiving.
Normal would be only one client socket who sends a command and then receives the reply of the server.
As usual, you are reading lines, but you aren't sending lines.
Use println(), not print().
You also need to stop reading when you get an IOException, or when readLine() returns null.
Why there are two client sockets is another mystery.

Signalr with android client

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`

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".

android- single server/ multiple clients?

I'm working on programming a live support chatting here, but the problem I faced is how to this server I made is receiving only one client to chat with.
can any pro explain to me to make the server receive more than one client at same time ?
and there is another problem which is :
If I close the chat activity then come back to make new chat through the application, the server couldn't response to it.
any suggestion please ...
Server Side:
public class TCPServer extends Thread {
public static final int SERVERPORT = 7777;
private boolean running = false;
private PrintWriter mOut;
private OnMessageReceived messageListener;
public static void main(String[] args) {
//opens the window where the messages will be received and sent
ServerBoard frame = new ServerBoard();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
/**
* Constructor of the class
* #param messageListener listens for the messages
*/
public TCPServer(OnMessageReceived messageListener) {
this.messageListener = messageListener;
}
/**
* Method to send the messages from server to client
* #param message the message sent by the server
*/
public void sendMessage(String message){
if (mOut != null && !mOut.checkError()) {
mOut.println(message);
mOut.flush();
}
}
#Override
public void run() {
super.run();
running = true;
try {
System.out.println("S: Connecting...");
//create a server socket. A server socket waits for requests to come in over the network.
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
//create client socket... the method accept() listens for a connection to be made to this socket and accepts it.
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
try {
//sends the message to the client
mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
//read the message received from client
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//in this while we wait to receive messages from client (it's an infinite loop)
//this while it's like a listener for messages
while (running) {
String message = in.readLine();
if (message != null && messageListener != null) {
//call the method messageReceived from ServerBoard class
messageListener.messageReceived("Student: "+message);
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
serverSocket.close();
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the ServerBoard
//class at on startServer button click
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
for the client I separate them into two activities :
public class TCPMainActivity extends Activity
{
private ListView mList;
private ArrayList<String> arrayList;
private MyCustomAdapter mAdapter;
private TCPClient mTcpClient;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tcpmain);
arrayList = new ArrayList<String>();
final EditText editText = (EditText) findViewById(R.id.editText);
Button send = (Button)findViewById(R.id.send_button);
//relate the listView from java to the one created in xml
mList = (ListView)findViewById(R.id.list);
mAdapter = new MyCustomAdapter(this, arrayList);
mList.setAdapter(mAdapter);
// connect to the server
new connectTask().execute("");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = editText.getText().toString();
//add the text in the arrayList
arrayList.add("Student: " + message);
//sends the message to the server
if (mTcpClient != null) {
mTcpClient.sendMessage(message);
}
//refresh the list
mAdapter.notifyDataSetChanged();
editText.setText("");
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//in the arrayList we add the messaged received from server
arrayList.add("Managment: "+values[0]);
// notify the adapter that the data set has changed. This means that new message received
// from server was added to the list
mAdapter.notifyDataSetChanged();
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all courses
}
}
protected void onStop() { // TODO Auto-generated method stub
//mTcpClient.stopClient();
Log.e("TCP Client", "Stooped");
super.onStop();
}
protected void onStart() { // TODO Auto-generated method stub
super.onStart();
}
protected void onResume() { // TODO Auto-generated method stub
super.onResume();
//new connectTask().execute("");
}
/* public void onDestroy() { // TODO Auto-generated method stub
super.onDestroy();
}
*/
}
the second one is :
public class TCPClient {
private String serverMessage;
public static final String SERVERIP = "192.168.0.102"; //your computer IP address
public static final int SERVERPORT = 7777;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedReader in;
Socket socket;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TCPClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
* #param message text entered by client
*/
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient(){
mRun = false;
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
mRun = true;
try {
if (socket != null)
socket.close();
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
//receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
}
serverMessage = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
thanking you in advance.

Categories

Resources