Duplicate messages receiving in android smack 4.1 - android

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

Related

RFCOMM_CreateConnection - already opened state:2, RFC state:4, MCB state:5 - isConnected returns false and can't reconnect

I have the following code to connect to a Bluetooth device:
class BiSymConnectThread extends Thread {
BluetoothDevice mDevice;
public BiSymConnectThread(BluetoothDevice device) throws SecurityException, NoSuchMethodException {
mDevice = device;
UUID uuid = mDevice.getUuids()[0].getUuid();
try {
biSymSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e("Error", "Could not connect!");
}
}
public void cancel() {
interrupt();
try {
Log.i("Treadmill", "in connect thread cancellation");
if (biSymSocket != null) {
biSymSocket.close();
}
} catch (IOException localIOException) {
Log.e("Treadmill", "exception + " + localIOException.getMessage());
}
}
public void run() {
try {
if (biSymSocket.isConnected()) {
biSymSocket.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IOException();
}
}
biSymSocket.connect();
eventHandler.obtainMessage(MESSAGE_CONNECT_BISYM, 0, 0, "").sendToTarget();
BluetoothConnectionService.setSocket(biSymSocket);
BluetoothConnectionService.sendMessage(biSymSocket, "S");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("Error", "InterruptedException: " + e.getMessage(), e);
throw new IOException();
}
} catch (IOException e) {
Log.e("Error", "IOException: " + e.getMessage(), e);
eventHandler.obtainMessage(MESSAGE_ERRORCONNECT_BISYM, 0, 0, "").sendToTarget();
if (biSymSocket != null) {
try {
biSymSocket.close();
} catch (IOException e1) {
Log.e("Error", "Can't close socket!");
}
}
}
synchronized (this) {
biSymConnectThread = null;
}
}
}
If I attempt to reconnect to the device, I get the following error:
RFCOMM_CreateConnection - already opened state:2, RFC state:4, MCB state:5
In the other question asking about this error, someone mentions the isConnected() method. However, in my case, isConnected() returns false and the connection still fails.
Does anyone know what is the problem here? It appears this is some obscure error, since there doesn't seem to be anything on the web about this.

How to make a Bluetooth SPP connection process more reliable?

We are about to release the new version of our software, and for the version afterward, our goal is to make the connection process for our Bluetooth SPP connections more reliable. We use the RN42 module in our products, and currently, at times it may take more than one try to connect to our boards.
Here is my current code:
class ConnectThread extends Thread {
BluetoothDevice mDevice;
public ConnectThread(BluetoothDevice device) throws SecurityException, NoSuchMethodException {
mDevice = device;
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
btSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e("Error", "Could not create socket!");
}
}
public void cancel() {
interrupt();
try {
Log.i("Treadmill", "in connect thread cancellation");
btSocket.close();
} catch (IOException localIOException) {
Log.e("Treadmill", "exception + " + localIOException.getMessage());
}
}
public void run() {
btAdapter.cancelDiscovery();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("whatever", "InterruptedException: " + e.getMessage(), e);
}
try {
btSocket.connect();
Log.i("Treadmill", "After Connect");
} catch (IOException ioe) {
Log.i("Treadmill", "Trying Fallback");
try {
Method m;
try {
btSocket.close();
m = mDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class});
btSocket = (BluetoothSocket) m.invoke(mDevice, 1);
Thread.sleep(500);
btSocket.connect();
} catch (IllegalArgumentException e) {
Log.e("whatever", "IllegalArgumentException: " + e.getMessage(), e);
} catch (IllegalAccessException e) {
Log.e("whatever", "IllegalAccessException: " + e.getMessage(), e);
} catch (InvocationTargetException e) {
Log.e("whatever", "InvocationTargetException: " + e.getMessage(), e);
} catch (NoSuchMethodException e) {
Log.e("whatever", "NoSuchMethodException: " + e.getMessage(), e);
} catch (InterruptedException e) {
Log.e("whatever", "InterruptedException: " + e.getMessage(), e);
}
} catch (IOException ioe2) {
Log.e("Treadmill", "Failed to connect to Bluetooth device: " + ioe2.getMessage());
eventHandler.obtainMessage(MESSAGE_ERRORCONNECT, 0, 0, getResources().getString(R.string.connerr) + ": " + ioe2.getMessage()).sendToTarget();
try {
btSocket.close();
} catch (IOException localIOException2) {
Log.e("Error", "IO Exception!");
}
return;
}
}
eventHandler.obtainMessage(MESSAGE_CONNECT, 0, 0, "").sendToTarget();
synchronized (this) {
connectThread = null;
}
manageConnectedSocket(btSocket);
}
}
Even with the fallback to reflection the connection intermittently fails on some devices. I get the following error:
find_rfc_slot_by_id unable to find RFCOMM slot id: XX (XX being a number that increments on each attempted connection).
followed by this:
Failed to connect to Bluetooth device: read failed, socket might closed or timeout, read ret: -1
Does anyone know how to avoid these errors.
Interestingly, for comparison. I am testing on two tablets. One tablet, the Samsung Galaxy Tab 4 seems to work extremely well, while another, the Astro Tab A10, seems to be a bit more intermittent unless you wait several seconds between connecting and disconnecting.
For more reliable connection means even app was closed, Bluetooth should be keep connected in the background.
Below is the working solution I followed in my app to keep Bluetooth connection background.
First create a class which extends service, because service runs in the background even app closed until you call stopService or stopSelf methods
while starting BluetoothService class pass Bluetooth Mac address to connect and run in the background.
Sample code:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null){
String deviceg = intent.getStringExtra("bluetooth_device");
if (deviceg != null){
connectToDevice(deviceg);
}
}
return START_STICKY;
}
Below is the connect to device method which identifies mac Address into Bluetooth Device.
public synchronized void connectToDevice(String macAddress){
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddress);
if (mConnectedThread != null){
mConnectedThread.cancel();
mConnectedThread = null;
}
mConnectThread = new ConnectBtThread(device);
toast("connecting");
mConnectThread.start();
}
This is my Thread class inside BluetoothService which runs in a separate thread
Code:
private class ConnectBtThread extends Thread{
private final BluetoothSocket mSocket;
private final BluetoothDevice mDevice;
public ConnectBtThread(BluetoothDevice device){
mDevice = device;
BluetoothSocket socket = null;
try {
socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(B_UUID));
} catch (IOException e) {
e.printStackTrace();
}
mSocket = socket;
}
#Override
public void run() {
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
try {
mSocket.connect();
Log.d("service","Bluetooth one running (connected)");
} catch (IOException e) {
try {
mSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
connected(mSocket);
}
public void cancel(){
try {
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It works perfectly fine for our app.
If you want to access service methods bind this service to your activity

not getting offline messages with smack

I am trying a chat application with openfire,smack and android where offline messages are not working. if both the users are online, able to send and receive the messages correctly . But if user A is offline and user B sends a message, User A is not getting the sent message of B once he is online.Tried possible solutions from stackoverflow but none of them working. using the below code to retrieve the offline messages.
new Thread(){
public void run(){
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setSocketFactory(SocketFactory.getDefault())
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName("123.456.0.854")//service name
.setHost("123.456.0.854") // host name
.setPort(5222) //port
.setUsernameAndPassword("phone", "admin")
.setConnectTimeout(40000)
.setCompressionEnabled(false).build();
connection = new XMPPTCPConnection(config);
try {
connection.connect();
connection.login("phone", "admin");
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("Available");
try {
connection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
try {
System.out.println("Count is " +offlineMessageManager.getMessageCount());
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}.start();
After lot struggle, I have resolved the issue. In your openfire admin page, go to "client settings" and reduce the idle time from 360sec (by default) to 1 sec(may be). Only then when you disconnected from Internet, it can detect that you are offline and preserve rest of the messages as OFFLINE.
#Override public void onNetworkConnectionChanged(boolean isConnected) {
if(isConnected){
new Thread() {
public void run() {
try {
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
builder.setUsernameAndPassword("phone", "admin");
builder.setSendPresence(true);
builder.setServiceName(<Service name>);
builder.setHost(<Host name>);
builder.setResource("Test");
builder.setDebuggerEnabled(true);
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("Available");
connection = new XMPPTCPConnection(builder.build());
connection.connect();
connection.login();
Presence presence123 = new Presence(Presence.Type.available);
presence123.setStatus("Available");
try {
connection.sendStanza(presence123);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
StanzaFilter filter = new AndFilter(new StanzaTypeFilter(Message.class));
PacketListener myListener = new PacketListener()
{
public void processPacket(Stanza stanza)
{
retrieveMessage(stanza,userType);
}
};
connection.addPacketListener(myListener, filter);
try {
connection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
} catch (SmackException | XMPPException | IOException e) {
e.printStackTrace();
}
//return connection.isConnected();
}
}.start();
The above is working fine and able to retrieve the offline messages. The method "retrieveMessage(stanza,userType);" is used to process the incoming message and update the Adapter. Make sure to send the Presence as "Available" when you reconnect. Please let me know if there are still any issues.

Error while trying to connect openfire using smack on android

XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword("test", "test");
configBuilder.setResource("test");
configBuilder.setServiceName("37.139.26.142");
configBuilder.setHost("37.139.26.142");
configBuilder.setPort(5222);
configBuilder.setSendPresence(true);
configBuilder.setDebuggerEnabled(true);
configBuilder.setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.required );
SASLMechanism mechanism = new SASLDigestMD5Mechanism();
SASLAuthentication.registerSASLMechanism(mechanism);
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.unBlacklistSASLMechanism("DIGEST-MD5");
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
try {
connection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
try {
connection.login();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I'm currently trying to handshake my android application and my openfire server(working on ubuntu). But I couldnt. I dont get any fail or something. Just nothing happens. And that feels bad.
Did you try to send a message? Are you sure that you are not connected?
Did you check on Openfire admin that your test user is not connected?
First I suggest you to try to send a message:
ChatManager chatmanager = ChatManager.getInstanceFor(connection);
Chat newChat = chatmanager.createChat("anotheruser#yourdomain", 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");
}
I got this code from : http://www.igniterealtime.org/builds/smack/docs/latest/documentation/messaging.html
Another suggestion is to disable the SecurityMode, just for a test.
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
If nothing of this works, try to use the configuration below, which works for me.
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serverAddress);
config.setHost(serverAddress);
config.setPort(5222);
config.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(config.build());
try {
connection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
try {
connection.login(loginUser, passwordUser);
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
First I find out this is not about Android part, this is about Openfire part. Because I couldnt connect it with Spark and I saw this in Logcat;
W/System.err: org.jivesoftware.smack.SmackException$ConnectionException: The following addresses failed: '37.139.26.142:5222' failed because java.net.SocketTimeoutException: failed to connect to /37.139.26.142 (port 5222) after 30000ms
Then I did some research and tried somethings and I saw it is about Ubuntu(at least for me). Then I moved my openfire server to Centos. Then I could be able to connect with Spark to it. Then I got another problem.
org.jivesoftware.smack.SmackException: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
And I solved this problem with this code below. I hope this can help others.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SmackConfiguration.DEBUG = true;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword("test", "test");
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("test");
configBuilder.setServiceName("enter your server ip here");
configBuilder.setHost("eneter your server ip here");
configBuilder.setPort(5222);
configBuilder.setSendPresence(true);
configBuilder.setDebuggerEnabled(true);
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
SASLAuthentication.unBlacklistSASLMechanism("PLAIN");
XMPPTCPConnection connection;
connection = new XMPPTCPConnection(configBuilder.build());
// Connect to the server
try {
connection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
// Log into the server
try {
connection.login();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

exception while trying to receive a file from server

i run some code to connect to a server, send it an Object and then receive another Object.
while running this on my Android enulator (v2.2) i get - java.net.SocketException: Socket is closed
the connection to the server is successful and i'm able to send the object but when i'm trying to do socket.getInputStream() it throws the exception
this is my connector class:
public class ConnectionToServer {
UserProblemRequest sentProblem;
Problem responseProblem;
Socket socket;
public ConnectionToServer(){
sentProblem = null;
responseProblem = null;
socket = null;
}
public void connect(){
try {
Log.d(TAG, "Connecting...");
socket = new Socket(Utils.SERVER_IP, Utils.SERVER_PORT);
Log.d(TAG, "SUCCESS: Connected!");
} catch (UnknownHostException e) {
Log.d(TAG, "ERROR: Falied to connect! (UnknownHostException)");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "ERROR: Falied to connect! (IOException)");
e.printStackTrace();
}
}
public void setProblemFromByteArray(byte[] data, boolean isFile){
sentProblem = new UserProblemRequest();
sentProblem.fileBArray = data.clone();
if (isFile){
sentProblem.requestType = Utils.requestType_IMAGE;
}
else {
sentProblem.requestType = Utils.RequestType_STRING;
}
}
public void sendProblem(){
ObjectOutputStream os;
try {
os = new ObjectOutputStream(socket.getOutputStream());
Log.d(TAG, "Sending file to server...");
os.writeObject(sentProblem);
os.flush();
os.close();
} catch (IOException e) {
Log.d(TAG, "ERROR: Falied to send file to server!");
e.printStackTrace();
}
Log.d(TAG, "SUCCESS: File sent to server!");
}
public void closeConnection(){
try {
socket.close();
} catch (IOException e) {
Log.d(TAG, "failed to close socket");
e.printStackTrace();
}
}
public Problem reciveResponseFromServer(){
ObjectInputStream ois;
try {
ois = new ObjectInputStream(socket.getInputStream());
responseProblem = (Problem) ois.readObject();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return responseProblem;
}
}
and i use this code to run it:
ConnectionToServer serverConnection = new ConnectionToServer();
serverConnection.connect();
serverConnection.setProblemFromByteArray(temp_data, true);
serverConnection.sendProblem();
Problem responseProblem = serverConnection.reciveResponseFromServer();
serverConnection.closeConnection();
any ideas?
Does closing the ObjectOutputStream() in sendProblem() wind up closing the underlying socket so that when you getInputStream() in reciveResponseFromServer() the socket is already closed?

Categories

Resources