I'm developing an Android app that is going to send camera stream to a Node.js web server by Socket. When the app has to create the socket the app doesn't execute the code inside the try statement but even though launchs any catch exception.
MyThread.java
protected Void doInBackground(Void... unused) {
OutputStream os = null;
try {Log.d("MyCameraApp", "HERE1");
mSocket = new Socket(ip, port);
if (mSocket != null) {Log.d("MyCameraApp", "SOCKET CONNECTED");
try {
os = mSocket.getOutputStream();
while (true) {
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(4);
dos.writeUTF("####");
dos.writeInt(mFrameBuffer.size());
dos.writeUTF("-##-");
dos.flush();
dos.write(mFrameBuffer.toByteArray());
dos.flush();
Thread.sleep(1000 / 15);
}
} catch (Exception e) {
e.printStackTrace();
try {
if (os != null)
os.close();
} catch (Exception e2) {
e.printStackTrace();
}
}
}
else {
Log.d("MyCameraApp", "SOCKET NULL");
}
}
catch(UnknownHostException e) {
Log.d("MyCameraApp", "CATCH SOCKET");
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
CameraActivity.java
try {
mThread = new MyThread(getApplicationContext(), SERVERIP, SERVERPORT);
mThread.execute();Log.d("MyCameraApp", "WELL DONE");
}
catch(Exception e) {
e.printStackTrace();
Log.d("MyCameraApp", "CATCH");
}
The CameraActivity create a mThread object and the app only displays the log 'HERE1' inside the try, before the socket is created and then displays the log 'WELL DONE'.
I have a basic Node.js server that only is listening in the correspondent port, nothing else.
What is wrong?
Thanks in advance!
The Android device was connected by wifi and the pc was connected by Ethernet... differents subnets.
I have looked all over for a solution to this problem, I have not come up with a solution that works.
Currently, I send and receive packets on my android device emulator using my loopback/localHost address. This proccess works successfuly, however when I try running the same code using my computer's public address the server never receives the packets.
private String hostName = "99.248.222.229";
//private String hostName = "10.0.2.2";
private InetAddress hostAddress;
#Override
protected void onCreate(Bundle savedInstanceState)
{
CreateAddress addressGetter = new CreateAddress();
try {
hostAddress = addressGetter.execute(hostName).get();
} catch(Exception e){
e.printStackTrace();
}
Button btnLock = (Button) findViewById(R.id.btnLock);
btnLock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendReceiveTask = new runUdpClient();
byte[] udpMsg = {(byte)housenumber, (byte)doornumber, LK_MSG, UNLOCK};
System.out.println(hostAddress);
sendPacket = new DatagramPacket(udpMsg, udpMsg.length, hostAddress, portnumber);
DatagramPacket receivePacket = null;
try {
receivePacket = sendReceiveTask.execute(sendPacket).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
currentDoorState = (receivePacket.getData()[3]==UNLOCK);
updateDoorStatus(currentDoorState);
int doorNum = doornumber;
eventArrayList.add(0, (getCurrentTimeStamp() + eventString.replace("doornum", Integer.toString(doorNum)))+ ((currentDoorState) ? "unlocked." : "locked."));
adapter.notifyDataSetChanged();
}
});
}
private class runUdpClient extends AsyncTask<DatagramPacket, Void, DatagramPacket>{
#Override
protected DatagramPacket doInBackground(DatagramPacket ...params){
DatagramSocket ds = null;
//SEND
try {
ds = new DatagramSocket();
DatagramPacket dp;
//dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), hostAddress, portnumber);
dp = params[0];
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//RECEIVE
DatagramPacket incomingPacket = new DatagramPacket(new byte[100], 100);
try {
ds.setSoTimeout(1000);
} catch (SocketException e) {
e.printStackTrace();
}
try {
ds.receive(incomingPacket);
} catch (IOException e){
e.printStackTrace();
}finally{
if(ds != null) ds.close();
}
System.out.println("Packet recieved from server" + Arrays.toString(incomingPacket.getData()));
return incomingPacket;
}
}
I have an Android application where I connect to a bluetooth device. When I shut the device off, the application tries to disconnect. So I try to close the inputstream the outputstream and the socket. Even though I have a try catch on each close try, the app crashes when it tries to close the inputstream. Any ideas? Code example:
private void resetConnection() {
if (mmInputStream != null) {
try {
mmInputStream.close();
} catch (Exception e) {
Log.e(LOG_TAG, "CANNOT CLOSE InputStream", e);
}
mmInputStream = null;
}
if (mmOutputStream != null) {
try {
mmOutputStream.close();
} catch (Exception e) {
Log.e(LOG_TAG, "CANNOT CLOSE OutputStream", e);
}
mmOutputStream = null;
}
if (mmSocket != null) {
try {
mmSocket.close();
} catch (Exception e) {
Log.e(LOG_TAG, "CANNOT CLOSE mmSocket", e);
}
mmSocket = null;
}
}
Any suggestions? Thanks
I have been trying to create an android chat app using smack 4.1. Message sending and receiving is working fine, but the problem is same message is getting several times with in the mXmppConnection.addAsyncStanzaListener.I don't know if i have missed to add something to the connection.
This is my connection class:
XMPPTCPConnectionConfiguration.Builder configBuilder = new XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(mUser, "password#123");
configBuilder.setPort(5555);
configBuilder.setServiceName("tvm.myname.com");
configBuilder.setDebuggerEnabled(true); configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
try
{
XMPPTCPConnection mConnection = new XMPPTCPConnection(configBuilder.build());
mConnection.connect();
mConnection.login();
}
catch (SmackException e)
{
}
And this the code where message receives:
mXmppConnection.addAsyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
Message message = (Message)packet;
Log.i("XMPPClient", "****** message " + message);
// code for handling message
} `enter code here`
},null);
The real problem is i am getting the message several times..the value of message is printing in the logs several time. Please help me....
FINALLY GOT SOLUTION
The issue is not with the client but due to careless coding. I have been assigning single instance of connection object to a class variable and listener is adding to these reference object every time. So that leads to calling listener multiple times....The fix is done by adding listener to the singleton connection object.
I don't know is there any best approach for keeping the xmpp connection stable through out the application.If anyone knows a better solution please post the answer here. I am using a global connection variable, all the chat operations are done by making use of this static connection variable. This is working for me.
For sending and receiving messages using smack we need to make connection with xmpp server.
public static AbstractXMPPConnection getInstance(Context context) {
mContext = context;
sendMessageCallBack = (XmppSendMessageCallBack) context;
if (mConnection == null) {
mInstance = new XmppClient();
mUser = new Preferences(context).getPhone();
setUserToServer();
}
return mConnection;
}
private static void setUserToServer() {
new Thread(new Runnable() {
#Override
public void run() {
try {
Looper.prepare();
/** connecting to server ***/
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setServiceName(Constants.HOST_URL);
configBuilder.setDebuggerEnabled(true);
configBuilder.setSendPresence(true);
configBuilder.setConnectTimeout(XMPPTCPConnectionConfiguration.DEFAULT_CONNECT_TIMEOUT);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
String[] sslProtocols = {"starttls"
, "no_sslv3"
, "no_tlsv1"};
configBuilder.setEnabledSSLProtocols(sslProtocols);
mConnection = new XMPPTCPConnection(configBuilder.build());
mConnection.setPacketReplyTimeout(120000);
mConnection.connect();
// Log into the server
if(mConnection!=null) {
mConnection.login(mUser, "password#123");
reConnectionSetUp();
PingManager pingManager = PingManager.getInstanceFor(mConnection);
pingManager.setPingInterval(60000);
pingManager.pingMyServer();
pingManager.registerPingFailedListener(new PingFailedListener() {
#Override
public void pingFailed() {
if (mConnection != null && !mConnection.isConnected())
setUserToServer();
}
});
setUpListenersForXmppConnection(mConnection);
}
} catch (SmackException.ConnectionException e) {
Log.e("XmppClient", "ConnectionException :", e);
Toast.makeText(mContext,"failed to connect to server",Toast.LENGTH_SHORT).show();
} catch (SmackException.NoResponseException e) {
Log.e("XmppClient", "NoResponseException :", e);
Toast.makeText(mContext,"Connection time out please try again",Toast.LENGTH_SHORT).show();
} catch (XMPPException e) {
Log.e("XmppClient", "XMPPException :", e);
}catch (IOException e) {
Log.e("XmppClient", "IOException :", e);
}catch (SmackException.NotConnectedException e) {
Log.e("XmppClient", "NotConnectedException :", e);
reConnectionSetUp();
}catch (SmackException e) {
Log.e("XmppClient", "SmackException :", e);
}catch (NullPointerException e) {
Log.e("XmppClient", "NullPointerException :", e);
}
}
}).start();
}
private static void setUpListenersForXmppConnection(AbstractXMPPConnection xmppConnection){
try {
if(xmppConnection!=null) {
sendOnlineStatus();
/** adding connection listener **/
xmppConnection.addConnectionListener(mInstance);
/** adding privacy manager to connection **/
if(xmppConnection!=null)
mPrivacyListManager = PrivacyListManager.getInstanceFor(xmppConnection);
/** adding packet listener for receving incoming packets **/
StanzaFilter filter = MessageTypeFilter.NORMAL;
if(xmppConnection!=null && mInstance!=null)
xmppConnection.addSyncStanzaListener(mInstance, null);
}
} catch (SmackException e) {
Log.e("XmppClient", "IOException :", e);
} catch (XMPPException e) {
Log.e("XmppClient", "XMPPException :", e);
e.printStackTrace();
} catch (NullPointerException e) {
Log.e("XmppClient", "NullPointerException :", e);
} catch (ConcurrentModificationException e){
Log.e("XmppClient", "ConcurrentModificationException :", e);
} catch (IllegalArgumentException e){
e.printStackTrace();
}catch (RetrofitError e){
Log.e("XmppClient", "RetrofitError :", e);
}
}
When we receive a message the following method will be invoked
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
if(packet instanceof Message) {
Message message = (Message) packet;
// Do your task
}
}
We can send message by creating a message object of smack like this,
Message message = new Message();
message.setFrom(senderId);
message.setBody(body);
message.setSubject(subject);
message.setTo(receiverId);
try {
if(mConnection!=null){
ChatManager chatManager = ChatManager.getInstanceFor(mConnection);
if(chatManager!=null){
chatManager.createChat(message.getTo(), new ChatStateListener() {
#Override
public void stateChanged(Chat chat, ChatState state) {
Log.e("XMPPClient", "******* stateChanged "+state);
}
#Override
public void processMessage(Chat chat, Message message) {
Log.e("XMPPClient", "******* processMessage "+message.getSubject());
}
}).sendMessage(message);
}
}
sendMessageCallBack.messageSuccessfullySend(message.getStanzaId(), status);
}catch (SmackException.NotConnectedException e){
Log.e("XMPPClient", "******* NotConnectedException ", e);
sendMessageCallBack.messageSendingFailed("");
}catch(NullPointerException e){
Log.e("XMPPClient", "******* NullPointerException ", e);
sendMessageCallBack.messageSendingFailed("");
}catch (Exception e){
sendMessageCallBack.messageSendingFailed("No Network");
}
Same problem I have faced but I got the solution, you don't unregistered your BroadcastReceiver when you logout from app below is code of logout and also you make all the connection is singleton.
try {
Presence pr=new Presence(Presence.Type.unavailable);
pr.setStatus(RoosterConnection.getConnection().getUser() + "false");
RoosterConnection.getConnection().sendStanza(pr);
if (mConnection != null) {
mConnection.disconnect();
}
// mBus.unregister(this);
mConnection = null;
// Unregister the message broadcast receiver.
if (uiThreadMessageReceiver != null) {
mApplicationContext.unregisterReceiver(uiThreadMessageReceiver);
uiThreadMessageReceiver = null;
}
Intent intent = new Intent(this,LoginActivity.class);
startActivity(intent);
finish();}catch(SmackException.NotConnectedException e){ e.printStackTrace();}catch(InterruptedException e){
e.printStackTrace();}
Just use addSyncStanzaListener instead addAsyncStanzaListener
I am trying to implement a simple socket that sends and receives strings from a server.
The following code is freezing the application, not sure if I have done something obviously wrong?
public String internetRoutesRetrieve(String userName) {
String command = null;
String response = null;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("Hidden IP", HiddenPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
command = "SEARCH <" + userName + ">";
dataOutputStream.writeUTF(command);
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
Thanks
Edit: It seems the program is freezing when I am trying to save the response from the server
see AsyncTask for proper client server communication on Android application.
you'd usualy get android.os.NetworkOnMainThreadException if you don't but I'd give it a try.