So I'm trying to receive a message from my server when there comes a notification from Google Cloud Messaging (GCM). My code is the following:
public class GcmIntentService extends IntentService {
//This class is executed by the BradcastReceiver when the devices
//gets a message from GCM
public static final int NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType();
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.i("INTENTSERVICE", extras.toString());
sendNotification(extras);
}
Log.e("WAKELOCK","Wakelock will end");
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
}
private void sendNotification(final Bundle extras){
Socket socket = null;
FileOutputStream fileStream;
MessageSet ms = null;
try {
socket = new Socket(getString(R.string.server_address), 37133);
Tools.sendDataToServer(getApplicationContext(),
socket,
MessageTypes.PULLMESSAGE,
extras.getString("content")); //sending does perfectly work
//Receive contents of Message
DataInputStream dis =
new DataInputStream(socket.getInputStream()); // but now is doesn't
//want to do more and the exception is thrown
byte type = dis.readByte();
/* doing things */
} catch (IOException e) {
e.printStackTrace();
} finally {
//Tools.close(socket);
}
/* post notification */
}
}
I can create the Socket and send Data to the server, wich is also received, but when I want to receive data on the phone afterwards, it gives an java.net.SocketException: Socket is closed Exception. But at the same time, the server is still sending data and the socket on the phone is also still open (according to debugger [PIC]).
But why does this Error occur?
The requested code of
Tools.sendDataToServer
public static void sendDataToServer(Context context, Socket socket, int messageType, String content){
try {
SharedPreferences prefs = context.getSharedPreferences(context.getString(R.string.SharedPrefs),0);
OutputStream out = socket.getOutputStream();
out.write(messageType);
byte[] msgBytes = (prefs.getString("userID","") + "|;" + prefs.getString("userSession","") + "|;" + content).getBytes("UTF-8");
Tools.writeDataLengthToStream(out, msgBytes.length);
out.write(msgBytes,0,msgBytes.length);
out.flush();
//out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When out.close() is commented out, it is working. Thats a problem I already had, but I still don't have a clue why it is like this.