Smack 4.1 No Response within reply timeout - java

I am using the following code in my android app:
Thread d = new Thread(new Runnable() {
#Override
public void run() {
SmackConfiguration.setDefaultPacketReplyTimeout(10000);
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("admin", "password")
.setServiceName("192.168.0.200")
.setHost("192.168.0.200")
.setPort(5223).setSecurityMode(SecurityMode.ifpossible)
.build();
AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
try {
conn2.connect();
conn2.login();
Presence presence = new Presence(Presence.Type.unavailable);
presence.setStatus("Gone fishing");
// Send the packet (assume we have an XMPPConnection instance called "con").
conn2.sendStanza(presence);
} catch (SmackException | IOException | XMPPException e) {
e.printStackTrace();
Log.d("TAG", e.toString());
}
ChatManager chatmanager = ChatManager.getInstanceFor(conn2);
Chat newChat = chatmanager.createChat("harsh#192.168.0.200");
try {
newChat.sendMessage("Howdy!");
}
catch (NotConnectedException e) {
e.printStackTrace();
}
}
});
d.start();
This is returning this error:
05-14 18:07:48.030: D/TAG(19470):
org.jivesoftware.smack.SmackException$NoResponseException: No response
received within reply timeout. Timeout was 10000ms (~10s). Used
filter: No filter used or filter was 'null'.
I have set up a local server at 192.168.0.200. Could anybody tell me what the problem is?
I am using these libraries:

I have successfully connected to local openfire server and logged in without SSL. Here is my code
public class NewClientActivity extends Activity {
EditText etUsername, etPassword;
Button bSubmit;
AbstractXMPPConnection mConnection;
ConnectionListener connectionListener = new ConnectionListener() {
#Override
public void connected(XMPPConnection xmppConnection) {
Log.d("xmpp", "connected");
try {
SASLAuthentication.registerSASLMechanism(new SASLMechanism() {
#Override
protected void authenticateInternal(CallbackHandler callbackHandler) throws SmackException {
}
#Override
protected byte[] getAuthenticationText() throws SmackException {
byte[] authcid = toBytes('\u0000' + this.authenticationId);
byte[] passw = toBytes('\u0000' + this.password);
return ByteUtils.concact(authcid, passw);
}
#Override
public String getName() {
return "PLAIN";
}
#Override
public int getPriority() {
return 410;
}
#Override
public void checkIfSuccessfulOrThrow() throws SmackException {
}
#Override
protected SASLMechanism newInstance() {
return this;
}
});
mConnection.login();
} catch (XMPPException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this, "Incorrect username or password", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void authenticated(XMPPConnection xmppConnection, boolean b) {
Log.d("xmpp", "authenticated");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClientActivity.this,"Logged in successfully...",Toast.LENGTH_LONG ).show();
}
});
}
#Override
public void connectionClosed() {
Log.d("xmpp", "connection closed");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("xmpp", "cononection closed on error");
}
#Override
public void reconnectionSuccessful() {
Log.d("xmpp", "reconnection successful");
}
#Override
public void reconnectingIn(int i) {
Log.d("xmpp", "reconnecting in " + i);
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("xmpp", "reconnection failed");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_client);
findViews();
}
private void findViews() {
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bSubmit = (Button) findViewById(R.id.bSubmit);
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] params = new String[]{etUsername.getText().toString(), etPassword.getText().toString()};
new Connect().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
}
});
}
class Connect extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
XMPPTCPConnectionConfiguration config = null;
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setServiceName("192.168.1.60").setHost("192.168.1.60")
.setDebuggerEnabled(true)
.setPort(5222)
.setUsernameAndPassword(params[0], params[1])
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setCompressionEnabled(false);
config = builder.build();
mConnection = new XMPPTCPConnection(config);
try {
//mConnection.setPacketReplyTimeout(10000);
mConnection.addConnectionListener(connectionListener);
mConnection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
}
}

I just removed .setPort from my request and it worked :
private class MyLoginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// Create a connection to the jabber.org server.
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setUsernameAndPassword(USERNAME, PASSWORD)
.setHost(HOST)
//.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName(HOST)
.setDebuggerEnabled(true) // to view what's happening in detail
.build();
AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);
conn1.setPacketReplyTimeout(30000);
try {
conn1.connect();
if(conn1.isConnected()) {
Log.w("app", "conn done");
}
conn1.login();
if(conn1.isAuthenticated()) {
Log.w("app", "Auth done");
}
}
catch (Exception e) {
Log.w("app", e.toString());
}
return "";
}
#Override
protected void onPostExecute(String result) {
}
}

Try this :
public static void main(String[] args) throws IOException, XMPPException, SmackException, NoSuchAlgorithmException {
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setServiceName("olx.intr")
.setDebuggerEnabled(true)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setHost("10.2.2.107")
.setPort(5222)
.setUsernameAndPassword("dhiren","olxindia")
.build();
AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
conn2.connect();
SASLMechanism mechanism = new SASLDigestMD5Mechanism();
SASLAuthentication.registerSASLMechanism(mechanism);
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.unBlacklistSASLMechanism("DIGEST-MD5");
try {
conn2.login();
}catch (Exception e){
e.printStackTrace();
}
boolean authenticated = conn2.isAuthenticated();
System.out.println(authenticated);
}

Related

Unable to invoke target function on server side using SignalR Android client. java.lang.reflect.InvocationTargetException

I am using signalR android client in my app. The code was working fine all of a sudden, my code is unable to invoke server side funcitons. It gives java.lang.reflect.InvocationTargetException exception.
Here is my code,
public class SignalRService extends Service {
private microsoft.aspnet.signalr.client.hubs.HubConnection mHubConnection;
private microsoft.aspnet.signalr.client.hubs.HubProxy mHubProxy;
private Handler mHandler; // to display Toast message
private final IBinder mBinder = new LocalBinder(); // Binder given to clients
public static final String BROADCAST_ACTION = "com.android.com.simplechatwithsignalr";
public SignalRService() {
}
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler(Looper.getMainLooper());
// GlobalBus.getBus().register(this);
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable e) {
Log.i("hoo", "uncaughtException: " + e.getMessage());
}
});
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);
SubsrciptionHandlerAsync subsrciptionHandlerAsync = new SubsrciptionHandlerAsync();
subsrciptionHandlerAsync.execute("run");
return result;
}
#Override
public void onDestroy() {
try {
mHubConnection.stop();
} catch (Exception e) {
Log.i("destroying connection", "onDestroy: " + e.getMessage());
}
// GlobalBus.getBus().unregister(this);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// Return the communication channel to the service.
// startSignalR();
return mBinder;
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public SignalRService getService() {
// Return this instance of SignalRService so clients can call public methods
return SignalRService.this;
}
}
/**
* method for clients (activities)
*/
public void startSignalR() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String serverUrl = "https://signalr.shifa4u.com/";
serverUrl = serverUrl + "signalr";
String CONNECTION_QUERYSTRING = "access_token=" + "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjYzNyIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJzaGFoaWQubXJkQGhvdG1haWwuY29tIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS9hY2Nlc3Njb250cm9sc2VydmljZS8yMDEwLzA3L2NsYWltcy9pZGVudGl0eXByb3ZpZGVyIjoiQVNQLk5FVCBJZGVudGl0eSIsIkFzcE5ldC5JZGVudGl0eS5TZWN1cml0eVN0YW1wIjoiMDY0Mjk4YTktNWIzNy00MGIxLWI1OTEtMzQwNGUzYTQ5YTE5IiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiQ3VzdG9tZXIiLCJ1aWQiOiIyNjM3IiwibmJmIjoxNTUxNzg4NDc2LCJleHAiOjE1NTI5OTgwNzYsImlzcyI6Imh0dHBzOi8vYXBpLnNoaWZhNHUuY29tIiwiYXVkIjoiYWFkNGRjMDczOWI2NGM1MjlhYjg2YzIxMjZlZDM0MWMifQ.q0OAU8L9YRjkP5ampzdp7Ji8Vy-Wjd0Wf0hs3kTg3pg" + "&Is_Guest_User=NO";
mHubConnection = new microsoft.aspnet.signalr.client.hubs.HubConnection(serverUrl, CONNECTION_QUERYSTRING, false, new Logger() {
#Override
public void log(String message, LogLevel level) {
System.out.println(message);
}
});
mHubConnection.connected(new Runnable() {
#Override
public void run() {
System.out.println("CONNECTED");
Log.i("Initail Connect", "run: " + "Initial Connect");
}
});
mHubConnection.closed(new Runnable() {
#Override
public void run() {
Log.i("CLosed", "run: Disconnected");
}
});
mHubConnection.error(new ErrorCallback() {
#Override
public void onError(Throwable throwable) {
Log.i("Signal R throwable", "onError: " + throwable);
}
});
String SERVER_HUB_CHAT = "IntegratedHUB";
mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException | ExecutionException e) {
Log.e("SimpleSignalR", e.toString());
return;
}
try {
welcome();
// welcome();
} catch (Exception e) {
Log.i("Exception", "startSignalR: " + e.getMessage());
}
mHubProxy.on("connectionSucceeded", new SubscriptionHandler1<String>() {
#Override
public void run(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "connectionSucceeded", Toast.LENGTH_SHORT).show();
Log.i("connectionSucceeded", "run: " + "connectionSucceeded");
invokeUpdateCall("");
}
});
}
}, String.class);
mHubProxy.on("guestConnectionSucceeded", new SubscriptionHandler1<String>() {
#Override
public void run(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "guest", Toast.LENGTH_SHORT).show();
Log.i("connectionSucceeded", "run: " + "guest");
invokeUpdateCall("");
}
});
}
}, String.class);
mHubProxy.on("organizerConnectedForMobileClient", new SubscriptionHandler3<Long, String, String>() {
#Override
public void run(Long urgentCallId, String token, String resourceId) {
Log.i("organizerConnected", "run: " + "organizerConnected");
// Toast.makeText(SignalRService.this, "Organizer connected", Toast.LENGTH_SHORT).show();
/* Shifa4U.mySharePrefrence.setUrgentCallId(urgentCallId);
Shifa4U.mySharePrefrence.setToken(token);
Shifa4U.mySharePrefrence.setResourceId(resourceId);
mHandler.post(new Runnable() {
#Override
public void run() {
Events.ConnectWithDoctor connectWithDoctor =
new Events.ConnectWithDoctor("");
GlobalBus.getBus().post(connectWithDoctor);
}
});*/
}
}, Long.class, String.class, String.class);
mHubProxy.on("connectionFailed", new SubscriptionHandler1<String>() {
#Override
public void run(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Connnection Failed", Toast.LENGTH_SHORT).show();
}
});
}
}, String.class);
mHubProxy.on("greatMessage", new SubscriptionHandler1<String>() {
#Override
public void run(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Greatest message " + msg, Toast.LENGTH_SHORT).show();
}
});
}
}, String.class);
}
public void invokeOnConnectedHub(String message) {
String SERVER_METHOD_SEND = "OnConnectedHub";
if (mHubConnection.getState().toString().equals("Connected")) {
try {
mHubProxy.invoke(SERVER_METHOD_SEND).done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
System.out.println("SENT!");
}
});
} catch (Exception e) {
Log.i("", "On Connected HUB: " + e.getMessage());
}
}
}
public void welcome() {
String SERVER_METHOD_SEND = "Welcome";
if (mHubConnection.getState().toString().equals("Connected")) {
try {
mHubProxy.invoke(SERVER_METHOD_SEND).done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
System.out.println("SENT!");
}
});
} catch (Exception e) {
Log.i("", "On Connected HUB: " + e.getMessage());
}
}
}
public void invokeUpdateCall(String message) {
String SERVER_METHOD_SEND = "UpdateCallRoom";
// mHubProxy.invoke(SERVER_METHOD_SEND);
try {
mHubProxy.invoke(SERVER_METHOD_SEND).done(new Action<Void>()
{
#Override public void run(Void obj) throws Exception
{
System.out.println("SENT!");
}
});
}
catch (Exception e)
{
Log.i("", "UpdateCallRoom: "+e.getMessage());
}
}
}
class SubsrciptionHandlerAsync extends AsyncTask {
#Override
protected String doInBackground(String... strings) {
try {
SignalRService signalRService = new SignalRService();
signalRService.startSignalR();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
Here is the stack trace.
I/System.out: serverSentEvents - Found new data: data: {"C":"d-8BC122A6-B,1F|IU,0|IV,1","M":[{"H":"IntegratedHUB","M":"greatMessage","A":["Welcome"]}]}
serverSentEvents - Trigger onData: {"C":"d-8BC122A6-B,1F|IU,0|IV,1","M":[{"H":"IntegratedHUB","M":"greatMessage","A":["Welcome"]}]}
HubConnection - Received data:
I/System.out: MessageId received: d-8BC122A6-B,1F|IU,0|IV,1
Invoking OnReceived with: null
HubConnection - Processing message
I/System.out: HubConnection - Getting HubInvocation from message
I/System.out: HubConnection - Message for: integratedhub
I/System.out: HubConnection - Invoking event: greatmessage with arguments
["Welcome"]
I/System.out: HubConnection - Error: java.lang.reflect.InvocationTargetException
I/Signal R throwable: onError: java.lang.reflect.InvocationTargetException
I/System.out: serverSentEvents - Response received
serverSentEvents - Read response to the end
I/System.out: serverSentEvents - Trigger onData with data: {"I":"0"}
On function not works and throw exception when it calls. Use subscribe function instead of that. That's work for me.
hub.subscribe("name of your event").addReceivedHandler(new Action<JsonElement[]>(){
#Override
public void run(JsonElement obj) throws Exception {
// do something
}
});

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.io.InputStream.read(byte[])' on a null object reference

I am trying to create a Chat Application using WiFip2p.Everything is done in this application. Before send and receive message app was working good. After that, I got this error. I am getting this error when I connect to another device. It shows a null object reference. I don't know why I need a solution can anyone help me thank you.
public class WiFi_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wi_fi_);
FINDVIEWBYID();
CLICKLISTINER();
}
Handler handler=new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what)
{
case MESSAGE_READ:
byte[] readbuffer=(byte[])msg.obj;
String tempmez=new String(readbuffer,0,msg.arg1);
txt_message.setText(tempmez);
break;
}
return true;
}
});
private void FINDVIEWBYID() {
btn_onoff=findViewById(R.id.onOff);
btn_discover=findViewById(R.id.discover);
btn_send=findViewById(R.id.sendButton);
listView=findViewById(R.id.peerListView);
txt_connectionsts=findViewById(R.id.connectionStatus);
txt_message=findViewById(R.id.readMsg);
edit_message=findViewById(R.id.writeMsg);
wifiManager= (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiP2pManager= (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel=wifiP2pManager.initialize(this,getMainLooper(),null);
broadcastReceiver=new Wifi_broadcast_reciever(wifiP2pManager,channel,this);
intentFilter=new IntentFilter();
intentFilter.addAction(wifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(wifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(wifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(wifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
private void CLICKLISTINER() {
btn_onoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
btn_onoff.setText("ON");
}
else
{
wifiManager.setWifiEnabled(true);
btn_onoff.setText("OFF");
}
}
});
btn_discover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
wifiP2pManager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
txt_connectionsts.setText("Discovery Started");
}
#Override
public void onFailure(int reason) {
txt_connectionsts.setText("Discovery starting failuree"+String.valueOf(reason));
}
});
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final WifiP2pDevice wifiP2pDevice=devicearray[position];
WifiP2pConfig config=new WifiP2pConfig();
config.deviceAddress=wifiP2pDevice.deviceAddress;
wifiP2pManager.connect(channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(WiFi_Activity.this, "Connect with"+ wifiP2pDevice.deviceName, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(WiFi_Activity.this, "Not connected", Toast.LENGTH_SHORT).show();
}
});
}
});
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msz=edit_message.getText().toString();
sendRecieve.write(msz.getBytes());
}
});
}
WifiP2pManager.PeerListListener peerListListener=new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerslist) {
if (!peerslist.getDeviceList().equals(peers));
{
peers.clear();
peers.addAll(peerslist.getDeviceList());
devicename_array=new String[peerslist.getDeviceList().size()];
devicearray=new WifiP2pDevice[peerslist.getDeviceList().size()];
int index= 0;
for (WifiP2pDevice device:peerslist.getDeviceList())
{
devicename_array[index]=device.deviceName;
devicearray[index]=device;
index++;
}
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item,devicename_array);
listView.setAdapter(arrayAdapter);
}
if (peers.size()==0)
{
Toast.makeText(WiFi_Activity.this, "No discover show", Toast.LENGTH_SHORT).show();
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener=new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
final InetAddress owneraddress= info.groupOwnerAddress;
if (info.groupFormed && info.isGroupOwner)
{
txt_connectionsts.setText("Host");
serverclass=new Serverclass();
serverclass.start();
}
else if (info.groupFormed)
{
txt_connectionsts.setText("Client");
clientclass = new Clientclass(owneraddress);
clientclass.start();
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
public class Serverclass extends Thread
{
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
try {
serverSocket=new ServerSocket(1111);
socket=serverSocket.accept();
sendRecieve=new SendRecieve(socket);
sendRecieve.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Clientclass extends Thread
{
Socket socket;
String host_address;
public Clientclass(InetAddress hostaddress){
host_address=hostaddress.getHostAddress();
socket=new Socket();
sendRecieve=new SendRecieve(socket);
sendRecieve.start();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(host_address,1111),500);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendRecieve extends Thread
{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendRecieve(Socket skt)
{
socket=skt;
try {
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer=new byte[2048];
int bytes;
while (socket!=null)
{
try {
bytes=inputStream.read(buffer);
if (bytes>0)
{
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
Log.d("error",e.getMessage());
}
}
}
public void write(byte[] bytes)
{
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I am getting this error on this part of code:-
#Override
public void run() {
byte[] buffer=new byte[2048];
int bytes;
while (socket!=null)
{
try {
bytes=inputStream.read(buffer);
if (bytes>0)
{
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
Log.d("error",e.getMessage());
}
}
}
The only thing I can see as being an issue is that you're catching (and ignoring) errors from getInputStream() and getOutputStream(). The exception is stopping execution, so if getInputStream() errors out, it doesn't get set. Both of your streams would be null.
Since you're at least printing the stacktrace, check for other stacktraces before the actual crash. It may tell you more about what went wrong.
To get around this, I suggest not catching the exception and instead making the constructor throw IOException. If you catch it early, it will cause less problems for you later on.
Edit: I've looked at your classes a bit more, and I see that you don't set the address of the Socket in time. Do that before you get the data streams for it. Not using the fields will work.
private Socket socket;
public SendRecieve(Socket skt) {
this.socket = skt;
}
#Override
public void run() {
try {
InputStream in = socket.getInputStream();
... etc
} ...
}
You calling Sendreceiver start before Clientclas run executes, so the following is necessary:
public class Clientclass extends Thread {
Socket socket;
String host_address;
public Clientclass(InetAddress hostaddress){
host_address=hostaddress.getHostAddress();
socket=new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(host_address,1111),500);
sendRecieve=new SendRecieve(socket);
sendRecieve.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to register device token to smack 4.2?

Following is my code and I want to get push notification when my device is offline or app is killed.
When my app is background I want to get notify by XMPP ejabberd server
IQ Class
class MyCustomIQ extends IQ {
String token = SharedPreferenceManager.getValue(getApplicationContext(), "DEVICE_TOKEN");
protected MyCustomIQ() {
super("query", "urn:xmpp:registernoti");
}
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.rightAngleBracket();
xml.element("token", token);
xml.element("devicetpye", "android");
return xml;
}
}
On connected
#Override
public void connected(XMPPConnection connection) {
Log.e(TAG, "connected: ");
MyCustomIQ iq = new MyCustomIQ();
iq.setType(IQ.Type.set);
try {
abstractXMPPConnection.sendIqWithResponseCallback(iq, new StanzaListener() {
#Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
Log.e(TAG, "processStanza: " + packet.toString());
}
});
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Try following code for register device token on xmpp server
Register token stanza
<iq to="YourServer" type="set">
<register xmlns="https://android.googleapis.com/gcm" >
<key>API_KEY</key>
</register>
</iq>
1) way for register token
public void registerTokenTomod_gcm(final String deviceToken){
IQ iq=new IQ("register","https://android.googleapis.com/gcm") {
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.attribute("key",deviceToken);
xml.setEmptyElement();
return xml;
}
};
iq.setType(IQ.Type.set);
iq.setTo(AppConstants.CHAT_HOSTNAME);
debugLog("getpushDicsoInfo send stanza:"+iq.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(iq.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(iq);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
2) way to register token
public void registerTokenToXmpp(String deviceId,String deviceName,String deviceToken){
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(deviceToken);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceId);
FormField device_name = new FormField("device-name");
device_name.addValue(deviceName);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
UnRegister device token from server
private void unregisterToken(){
String deviceid="3524940..."; //sony
String tokenstring="GHkd7Ro2qtMg:XPA91bflkgklDeg..."; // sony
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(tokenstring);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceid);
FormField device_name = new FormField("device-name");
// device_name.addValue(devicename);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}

Keep MQTT Topics Subscribed onResume Activity

I've a MQTT Service Class, MyMqttService.class, runing when I log in in my app:
Intent intent = new Intent(getApplicationContext(), MyMqttService.class);
startService(intent);
Then I have various Activities and in one of them, I have switch buttons to select which channels I want to subscribe. In my onPause/onResume, I check which buttons are on and which are off and make them go to that same state when I come back to that Activity. The problem is, if there is at least one button on when I resume the Activity, I get an error and my aplication crashes, since my app tries to subscribe, and cant.
My service Class:
public class MyMqttService extends Service implements MqttCallback, IMqttActionListener {
private final IBinder binder = new MyBinder();
private MqttAndroidClient mqttClient;
private MqttConnectOptions mqttConnectOptions;
private static final MemoryPersistence persistence = new MemoryPersistence();
private ArrayList<MqttAndroidClient> lostConnectionClients;
private String clientId = "";
private boolean isReady = false;
private boolean doConnectTask = true;
private boolean isConnectInvoked = false;
private Handler handler = new Handler();
private final int RECONNECT_INTERVAL = 10000; // 10 seconds
private final int DISCONNECT_INTERVAL = 20000; // 20 seconds
private final int CONNECTION_TIMEOUT = 60;
private final int KEEP_ALIVE_INTERVAL = 200;
private String broker_url = "xxx.xxx.xxx.xxx";
public class MyBinder extends Binder {
public MyMqttService getService() {
return MyMqttService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
initMqttClient();
}
private void initMqttClient() {
if(mqttClient != null) {
mqttClient = null;
}
lostConnectionClients = new ArrayList<>();
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
mqttConnectOptions.setConnectionTimeout(CONNECTION_TIMEOUT);
mqttConnectOptions.setKeepAliveInterval(KEEP_ALIVE_INTERVAL);
setNewMqttClient();
handler.post(connect);
handler.postDelayed(disconnect, DISCONNECT_INTERVAL);
}
private void setNewMqttClient() {
mqttClient = new MqttAndroidClient(MyMqttService.this, broker_url, clientId, persistence);
mqttClient.setCallback(this);
}
public Runnable connect = new Runnable() {
public void run() {
connectClient();
handler.postDelayed(connect, RECONNECT_INTERVAL);
}
};
public Runnable disconnect = new Runnable() {
public void run() {
disconnectClients();
handler.postDelayed(disconnect, DISCONNECT_INTERVAL);
}
};
private void connectClient() {
if(doConnectTask) {
doConnectTask = false;
try {
isConnectInvoked = true;
mqttClient.connect(mqttConnectOptions, null, this);
} catch (MqttException ex) {
doConnectTask = true;
System.out.println("MQTT exception 1: " + ex.toString());
}
}
}
private void disconnectClients() {
if (lostConnectionClients.size() > 0) {
// Disconnect lost connection clients
for (MqttAndroidClient client : lostConnectionClients) {
if (client.isConnected()) {
try {
client.disconnect();
} catch (MqttException e) {
System.out.println("MQTT exception 2: " + e.toString() );
}
}
}
// Close already disconnected clients
for (int i = lostConnectionClients.size() - 1; i >= 0; i--) {
try {
if (!lostConnectionClients.get(i).isConnected()) {
MqttAndroidClient client = lostConnectionClients.get(i);
client.close();
lostConnectionClients.remove(i);
}
} catch (IndexOutOfBoundsException e) {
System.out.println("MQTT exception 3: " + e.toString());
}
}
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onSuccess(IMqttToken asyncActionToken) {
isReady = true;
// subscribe here
subscribe("");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
setNewMqttClient();
isReady = false;
doConnectTask = true;
isConnectInvoked = false;
}
public void subscribe(String topic) {
try {
mqttClient.subscribe(topic, 0);
isReady = true;
} catch (MqttSecurityException mqttSexEx) {
isReady = false;
} catch (MqttException mqttEx) {
isReady = false;
}
}
private void unsubscribe(String topic) {
try {
mqttClient.unsubscribe(topic);
} catch (MqttSecurityException mqttSecEx) {
System.out.println("MQTT exception 4: " + mqttSecEx.toString());
} catch (MqttException mqttEx) {
System.out.println("MQTT exception 5: " + mqttEx.toString());
}
}
private void publish(String topic, String jsonPayload) {
if(!isReady) {
return;
}
try {
MqttMessage msg = new MqttMessage();
msg.setQos(0);
msg.setPayload(jsonPayload.getBytes("UTF-8"));
mqttClient.publish(topic, msg);
} catch (Exception ex) {
System.out.println("MQTT exception 6: " + ex.toString());
}
}
#Override
public void connectionLost(Throwable cause) {
System.out.println("MQTT exception 7: " + cause.getMessage());
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
String payload = new String(message.getPayload());
// do something
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("MQTT exception 8: deliveryComplete()");
}
}
My activity with the swich buttons, where I subscribe:
public class DefinicoesActivity extends AppCompatActivity {
private Switch switchSaude;
private Switch switchAlimentacao;
private Switch switchDesporto;
private static Bundle bundle = new Bundle();
private String topico;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definicoes);
final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://5.196.27.244:1883", "users");
mqttAndroidClient.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
String payload = new String(message.getPayload());
String titulo = payload.substring(0, payload.indexOf("\n"));
System.out.println("mensagem receitas:" + titulo + " " + topic);
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
System.out.println("Connection Success!");
try {
System.out.println("Subscribing to /test");
mqttAndroidClient.subscribe("/test", 0);
System.out.println("Subscribed to /test");
} catch (MqttException ex) {
System.out.println("MQTT Definicoes excpetion: " + ex);
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
System.out.println("MQTT Definicoes excpetion 2:" + exception.toString());
}
});
} catch (MqttException ex) {
System.out.println("MQTT Definicoes excpetion 3:" + ex.toString());
}
switchSaude = findViewById(R.id.switchSaude);
switchAlimentacao = findViewById(R.id.switchAlimentacao);
switchDesporto = findViewById(R.id.switchDesporto);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setTitle("Definiçoes");
switchAlimentacao.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton View, boolean isChecked) {
if(!isChecked){
Snackbar.make(View, "Cancelou a subscrição de dicas sobre Receitas", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
else
{
topico = "Receitas";
try {
mqttAndroidClient.subscribe(topico, 1);
} catch (MqttException e) {
e.printStackTrace();
}
Snackbar.make(View, "Sobscreveu dicas sobre Receitas", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
}
});
switchDesporto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton View, boolean isChecked) {
if(!isChecked){
Snackbar.make(View, "Cancelou a subscrição de dicas sobre Desporto", Snackbar.LENGTH_LONG).show();
}
else
{
topico = "Desporto";
try {
mqttAndroidClient.subscribe(topico, 1);
} catch (MqttException e) {
e.printStackTrace();
}
Snackbar.make(View, "Sobscreveu dicas sobre Desporto", Snackbar.LENGTH_LONG).show();
}
}
});
switchSaude.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton View, boolean isChecked) {
if(!isChecked){
Snackbar.make(View, "Cancelou a subscrição de dicas sobre Saúde", Snackbar.LENGTH_LONG).show();
}
else
{
topico = "Saúde";
try {
mqttAndroidClient.subscribe(topico, 1);
} catch (MqttException e) {
e.printStackTrace();
}
Snackbar.make(View, "Sobscreveu dicas sobre Saúde", Snackbar.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onPause() {
super.onPause();
bundle.putBoolean("switchAlimentacaoState", switchAlimentacao.isChecked());
bundle.putBoolean("switchDesportoState", switchDesporto.isChecked());
bundle.putBoolean("switchSaudeState", switchSaude.isChecked());
}
#Override
protected void onResume() {
super.onResume();
final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://5.196.27.244:1883", "users");
if(bundle.getBoolean("switchAlimentacaoState")){
switchAlimentacao.setChecked(bundle.getBoolean("switchAlimentacaoState"));
topico = "Receitas";
try {
mqttAndroidClient.subscribe(topico, 1);
} catch (MqttException e) {
e.printStackTrace();
}
}
if(bundle.getBoolean("switchDesportoState")){
switchDesporto.setChecked(bundle.getBoolean("switchDesportoState"));
topico = "Desporto";
try {
mqttAndroidClient.subscribe(topico, 1);
} catch (MqttException e) {
e.printStackTrace();
}
}
if(bundle.getBoolean("switchSaudeState")){
switchDesporto.setChecked(bundle.getBoolean("switchSaudeState"));
topico = "Saúde";
try {
mqttAndroidClient.subscribe(topico, 1);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
}
My error:
12-27 12:06:30.264 20361-20361/com.support.android.iplfit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.support.android.iplfit, PID: 20361
java.lang.RuntimeException: Unable to resume activity {com.support.android.iplfit/com.support.android.iplfit.Activities.DefinicoesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void org.eclipse.paho.android.service.MqttService.subscribe(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3400)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2713)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void org.eclipse.paho.android.service.MqttService.subscribe(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String)' on a null object reference
at org.eclipse.paho.android.service.MqttAndroidClient.subscribe(MqttAndroidClient.java:906)
at org.eclipse.paho.android.service.MqttAndroidClient.subscribe(MqttAndroidClient.java:841)
at com.support.android.iplfit.Activities.DefinicoesActivity$3.onCheckedChanged(DefinicoesActivity.java:122)
at android.widget.CompoundButton.setChecked(CompoundButton.java:156)
at android.widget.Switch.setChecked(Switch.java:1074)
at com.support.android.iplfit.Activities.DefinicoesActivity.onResume(DefinicoesActivity.java:213)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6766)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3377)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2713) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

Can't send message and receive using java socket while connected to Network Service Discovery

I am using Network Service Discovery service to discovery peer and connected to them using socket so , so socket created successfully but i am not able to send message or receive message so below is my code
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private NSDHelper mNsdHelper;
private int port;
private Context mContext;
ChatConnection mConnection;
private Button mDiscover, advertise_btn, connect_btn;
private Handler mUpdateHandler;
private TextView mStatusView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStatusView = (TextView) findViewById(R.id.status);
mContext = MainActivity.this;
mUpdateHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String chatLine = msg.getData().getString("msg");
addChatLine(chatLine);
}
};
mConnection = new ChatConnection(mUpdateHandler);
mNsdHelper = new NSDHelper(this);
mNsdHelper.initNSD();
advertise_btn = (Button) findViewById(R.id.advertise_btn);
connect_btn = (Button) findViewById(R.id.connect_btn);
advertise_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Register service
if (mConnection.getLocalPort() > -1) {
mNsdHelper.registerService(mConnection.getLocalPort());
} else {
Log.d(TAG, "ServerSocket isn't bound.");
}
}
});
connect_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NsdServiceInfo service = mNsdHelper.getChosenServiceInfo();
if (service != null) {
Log.d(TAG, "Connecting.");
mConnection.connectToServer(service.getHost(),
service.getPort());
} else {
Log.d(TAG, "No service to connect to!");
}
}
});
mDiscover = (Button) findViewById(R.id.discover_btn);
mDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mNsdHelper.discoverServices();
}
});
}
public void clickSend(View v) {
EditText messageView = (EditText) this.findViewById(R.id.chatInput);
if (messageView != null) {
String messageString = messageView.getText().toString();
if (!messageString.isEmpty()) {
mConnection.sendMessage(messageString);
}
messageView.setText("");
}
}
public void addChatLine(String line) {
mStatusView.append("\n" + line);
}
#Override
protected void onPause() {
if (mNsdHelper != null) {
mNsdHelper.stopDiscovery();
}
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
if (mNsdHelper != null) {
mNsdHelper.discoverServices();
}
}
#Override
protected void onDestroy() {
mNsdHelper.tearDown();
mConnection.tearDown();
super.onDestroy();
}
}
ChatConnection
public class ChatConnection {
private Handler mUpdateHandler;
private ChatServer mChatServer;
private ChatClient mChatClient;
private static final String TAG = "ChatConnection";
private Socket mSocket;
private int mPort = -1;
public ChatConnection(Handler handler) {
mUpdateHandler = handler;
mChatServer = new ChatServer(handler);
}
public void tearDown() {
mChatServer.tearDown();
mChatClient.tearDown();
}
public void connectToServer(InetAddress address, int port) {
mChatClient = new ChatClient(address, port);
}
public void sendMessage(String msg) {
if (mChatClient != null) {
mChatClient.sendMessage(msg);
}
}
public int getLocalPort() {
return mPort;
}
public void setLocalPort(int port) {
mPort = port;
}
public synchronized void updateMessages(String msg, boolean local) {
Log.e(TAG, "Updating message: " + msg);
if (local) {
msg = "me: " + msg;
} else {
msg = "them: " + msg;
}
Bundle messageBundle = new Bundle();
messageBundle.putString("msg", msg);
Message message = new Message();
message.setData(messageBundle);
mUpdateHandler.sendMessage(message);
}
private synchronized void setSocket(Socket socket) {
Log.d(TAG, "setSocket being called.");
if (socket == null) {
Log.d(TAG, "Setting a null socket.");
}
if (mSocket != null) {
if (mSocket.isConnected()) {
try {
mSocket.close();
} catch (IOException e) {
// TODO(alexlucas): Auto-generated catch block
e.printStackTrace();
}
}
}
mSocket = socket;
}
private Socket getSocket() {
return mSocket;
}
private class ChatServer {
ServerSocket mServerSocket = null;
Thread mThread = null;
public ChatServer(Handler handler) {
mThread = new Thread(new ServerThread());
mThread.start();
}
public void tearDown() {
mThread.interrupt();
try {
mServerSocket.close();
} catch (IOException ioe) {
Log.e(TAG, "Error when closing server socket.");
}
}
class ServerThread implements Runnable {
#Override
public void run() {
try {
// Since discovery will happen via Nsd, we don't need to care which port is
// used. Just grab an available one and advertise it via Nsd.
mServerSocket = new ServerSocket(0);
setLocalPort(mServerSocket.getLocalPort());
while (!Thread.currentThread().isInterrupted()) {
Log.d(TAG, "ServerSocket Created, awaiting connection");
setSocket(mServerSocket.accept());
Log.d(TAG, "Connected.");
if (mChatClient == null) {
int port = mSocket.getPort();
InetAddress address = mSocket.getInetAddress();
connectToServer(address, port);
}
}
} catch (IOException e) {
Log.e(TAG, "Error creating ServerSocket: ", e);
e.printStackTrace();
}
}
}
}
private class ChatClient {
private InetAddress mAddress;
private int PORT;
private final String CLIENT_TAG = "ChatClient";
private Thread mSendThread;
private Thread mRecThread;
public ChatClient(InetAddress address, int port) {
Log.d(CLIENT_TAG, "Creating chatClient");
this.mAddress = address;
this.PORT = port;
mSendThread = new Thread(new SendingThread());
mSendThread.start();
}
class SendingThread implements Runnable {
BlockingQueue<String> mMessageQueue;
private int QUEUE_CAPACITY = 10;
public SendingThread() {
mMessageQueue = new ArrayBlockingQueue<String>(QUEUE_CAPACITY);
}
#Override
public void run() {
try {
if (getSocket() == null) {
setSocket(new Socket(mAddress, PORT));
Log.d(CLIENT_TAG, "Client-side socket initialized.");
} else {
Log.d(CLIENT_TAG, "Socket already initialized. skipping!");
}
mRecThread = new Thread(new ReceivingThread());
mRecThread.start();
} catch (UnknownHostException e) {
Log.d(CLIENT_TAG, "Initializing socket failed, UHE", e);
} catch (IOException e) {
Log.d(CLIENT_TAG, "Initializing socket failed, IOE.", e);
}
while (true) {
try {
String msg = mMessageQueue.take();
sendMessage(msg);
} catch (InterruptedException ie) {
Log.d(CLIENT_TAG, "Message sending loop interrupted, exiting");
}
}
}
}
class ReceivingThread implements Runnable {
#Override
public void run() {
BufferedReader input;
try {
input = new BufferedReader(new InputStreamReader(
mSocket.getInputStream()));
while (!Thread.currentThread().isInterrupted()) {
String messageStr = null;
messageStr = input.readLine();
if (messageStr != null) {
Log.d(CLIENT_TAG, "Read from the stream: " + messageStr);
updateMessages(messageStr, false);
} else {
Log.d(CLIENT_TAG, "The nulls! The nulls!");
break;
}
}
input.close();
} catch (IOException e) {
Log.e(CLIENT_TAG, "Server loop error: ", e);
}
}
}
public void tearDown() {
try {
getSocket().close();
} catch (IOException ioe) {
Log.e(CLIENT_TAG, "Error when closing server socket.");
}
}
public void sendMessage(String msg) {
try {
Socket socket = getSocket();
if (socket == null) {
Log.d(CLIENT_TAG, "Socket is null, wtf?");
} else if (socket.getOutputStream() == null) {
Log.d(CLIENT_TAG, "Socket output stream is null, wtf?");
}
PrintWriter out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(getSocket().getOutputStream())), true);
out.println(msg);
out.flush();
updateMessages(msg, true);
} catch (UnknownHostException e) {
Log.d(CLIENT_TAG, "Unknown Host", e);
} catch (IOException e) {
Log.d(CLIENT_TAG, "I/O Exception", e);
} catch (Exception e) {
Log.d(CLIENT_TAG, "Error3", e);
}
Log.d(CLIENT_TAG, "Client sent message: " + msg);
}
}
}
NSDHelper
public class NSDHelper {
private static final String TAG = NSDHelper.class.getSimpleName();
NsdManager mNsdManager;
public static final String SERVICE_TYPE = "_geoStorm._tcp.";
public String mServiceName = "DROIDDEVICE";
NsdManager.DiscoveryListener mDiscoveryListener;
NsdManager.RegistrationListener mRegistrationListener;
NsdManager.ResolveListener mResolveListener;
NsdServiceInfo mService;
private Context mContext;
public NSDHelper(Context _context) {
mContext = _context;
mNsdManager = (NsdManager) mContext.getSystemService(Context.NSD_SERVICE);
}
public void initNSD() {
initializeResolveListener();
initializeDiscoveryListener();
initializeRegistrationListener();
}
/**
* This method is to register NSD
*
* #param port
*/
public void registerService(int port) {
NsdServiceInfo nsdServiceInfo = new NsdServiceInfo();
nsdServiceInfo.setPort(port);
nsdServiceInfo.setServiceName(mServiceName);
nsdServiceInfo.setServiceType(SERVICE_TYPE);
mNsdManager.registerService(nsdServiceInfo, NsdManager.PROTOCOL_DNS_SD,
mRegistrationListener);
}
public void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
#Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "Resolve failed" + errorCode);
}
#Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.e(TAG, "Resolve Succeeded. " + serviceInfo);
if (serviceInfo.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same IP.");
return;
}
mService = serviceInfo;
}
};
}
public void initializeDiscoveryListener() {
mDiscoveryListener = new NsdManager.DiscoveryListener() {
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
#Override
public void onDiscoveryStarted(String serviceType) {
Toast.makeText(mContext, "Discovery Started Successfully ",
Toast.LENGTH_LONG).show();
Log.d(TAG, "Service discovery started");
}
#Override
public void onDiscoveryStopped(String serviceType) {
Log.i(TAG, "Discovery stopped: " + serviceType);
Toast.makeText(mContext, "Discovery stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onServiceFound(NsdServiceInfo serviceInfo) {
Log.d(TAG, "Service discovery success" + serviceInfo);
if (!serviceInfo.getServiceType().equals(SERVICE_TYPE)) {
Toast.makeText(mContext, "Unknown Service Type", Toast.LENGTH_LONG).show();
} else if (serviceInfo.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same machine: " + mServiceName);
} else if (serviceInfo.getServiceName().contains(mServiceName)) {
mNsdManager.resolveService(serviceInfo, mResolveListener);
}
Log.d(TAG, serviceInfo.getPort() + "");
// Log.d(TAG, new InetSocketAddress(serviceInfo.getHost());)
}
#Override
public void onServiceLost(NsdServiceInfo serviceInfo) {
Log.e(TAG, "service lost" + serviceInfo);
Toast.makeText(mContext, "service Lost" + serviceInfo, Toast.LENGTH_LONG).show();
if (mService == serviceInfo) {
mService = null;
}
}
};
}
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
}
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
}
#Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
mServiceName = serviceInfo.getServiceName();
}
#Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
}
};
}
public void discoverServices() {
if (mNsdManager != null)
mNsdManager.discoverServices(
SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
public void stopDiscovery() {
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
}
public NsdServiceInfo getChosenServiceInfo() {
return mService;
}
public void tearDown() {
mNsdManager.unregisterService(mRegistrationListener);
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
mNsdManager = null;
mRegistrationListener = null;
}
}
I need help in this that how i can send message using socket , coz i stuck i am not getting any nothing , any help would be appreciated.

Categories