Socket client. Sends message only when exiting the app

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

45 Replies - 6840 Views - Last Post: 22 March 2012 - 04:00 PM

#1 EndLessMind  Icon User is offline

  • These are the droids you're looking for
  • member icon

Reputation: 193
  • View blog
  • Posts: 1,097
  • Joined: 13-March 09

Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 08:27 AM

Hi.
I'm trying to make a socket client that connects to a server on my PC.
The connection is successful but when i hit the "send"-button it goes thought the code, but the server do not receive anything.
But when i use task-killer on my phone, then the messages is sent and the server receive the message.

Here is my code for that activity

package com.pontus.dev;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.onclickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class StartServer extends Activity {
	private EditText serverIP;
	private Button ConnectComp;
	private Button BtnSend;
	private String IpAddress;
	private boolean connected = false;
	private Socket socket;
	private DataInputStream _InPut;
	private DataOutputStream _OutPut;
	private Thread _listener;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client);
		
		serverIP = (EditText)findViewById(R.id.Server_ip);
		ConnectComp = (Button)findViewById(R.id.btnConnect);
		BtnSend = (Button)findViewById(R.id.btnSkicka);
		BtnSend.setonclickListener(SendListner);
		ConnectComp.setonclickListener(connectListener);
	}
	private onclickListener SendListner = new onclickListener() {
		public void onclick(View v) {
		
				sendMessage("Hej Server!");
		}
	};
	private onclickListener connectListener = new onclickListener() {
		public void onclick(View v) {
				if(!connected) {
				IpAddress = serverIP.getText().toString();
				
				if(!IpAddress.equals("")) {
					InetAddress serverAddr;
					try {
						serverAddr = InetAddress.getByName(IpAddress);
						Log.d("ClientActivity","C: Ansluter...");
						socket = new Socket(serverAddr, 4040);
						_InPut = new DataInputStream(socket.getInputStream());
						_OutPut = new DataOutputStream(socket.getOutputStream());
						_listener = new Thread(new ClientThread());
						Toast.makeText(getBaseContext(), "M1", 1000).show();
						_listener.start();
						Log.d("ClientActivity", "C: Ansluten.");
						Toast.makeText(getBaseContext(), "M2", 1000).show();
					} catch (Exception e) {
						Log.e("ClientActivity", e.getMessage());
					}
				}
				}
				}
		};
		
		public class ClientThread implements Runnable {
			public void run() {
				try {

					Log.d("ClientActivity", "Tråd startad");
					//connected = true;
					while (true) {
						try {
						Log.i("ClientActivity", "Väntar på meddelande från servern");
						String line = _InPut.readUTF();
						Log.i("ClientActivity", "Har mottaigt ett meddelande från servern: " + line);
						
						} catch (Exception e) {
							Log.e("ClientActivity", "S: Error " + e.getMessage(),e);
						}
					}
				} catch (Exception e) {
					Log.e("ClientActivity", "C: Error " + e.getMessage(), e);
				
				}
			}
		}
		
		public boolean sendMessage(String message){
			try {
				Log.i("ClientActivity", "Skickar meddelande till server :" + message);
				_OutPut.writeBytes(message);
				_OutPut.flush();
				Log.i("ClientActivity", "Meddelande ska vara skickat!");
				return true;
			}catch (Exception e){
				Log.e("ClientActivity", e.getMessage());
				_listener.interrupt();
			}
			return false;
		}
	}



Hope you understand my problem.
Thanks in advance :)

Is This A Good Question/Topic? 0
  • +

Replies To: Socket client. Sends message only when exiting the app

#2 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 276
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 10:18 AM

I think you need to call _OutPut.close(); after you flush your message to the server.
Was This Post Helpful? 1
  • +
  • -

#3 EndLessMind  Icon User is offline

  • These are the droids you're looking for
  • member icon

Reputation: 193
  • View blog
  • Posts: 1,097
  • Joined: 13-March 09

Re: Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 10:34 AM

Thanks, that worked :)
But i can only send the message once, then i get java.net.SocketException: Socket closed
But i don't have any "socket.Close();" in my code :o
Was This Post Helpful? 0
  • +
  • -

#4 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 276
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 10:42 AM

Calling close on the input stream causes the socket to close. Try using PrintWriter instead of DataOutputStream. I believe the DataOutputStream is buffering your data and not sending it untill either you fill the buffer up or cause the stream to close even thou you are call flush on it. After you are done sending all your data through your output steam you HAVE to close the stream but using PrintWriter should fix your problem of it not sending the data unless you close the connection!

This post has been edited by H3R3T1C: 27 November 2011 - 10:43 AM

Was This Post Helpful? 1
  • +
  • -

#5 EndLessMind  Icon User is offline

  • These are the droids you're looking for
  • member icon

Reputation: 193
  • View blog
  • Posts: 1,097
  • Joined: 13-March 09

Re: Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 04:44 PM

Thanks again :) That fixed the send part :)
But i got problem with reading incoming :(

I tried Log.d("ClientActivity","" + new BufferedReader(_InPut).readLine());
Where _InPut = InputStreamReader , but i don't get anything

If i try
Log.d("ClientActivity","" + InPut.read()));
then it display all the ascii values for each char in the incoming stream

I tried to convert socket.GetInPutStream() to string with this code
public String iStream_to_String(InputStream is1)
{
	 BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
	 String line;
	 StringBuilder sb =  new StringBuilder();
	 try {
		while ((line = rd.readLine()) != null) {
		 		sb.append(line);
		 }
		 rd.close();

	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 String contentOfMyInputStream = sb.toString();
	 return contentOfMyInputStream;
}



But still nothing.
the Logcat don't show anything.
It's like nothing happens :censored:

Here is my current code for my thread
	public class ClientThread implements Runnable {
			public void run() {
				try {

					Log.d("ClientActivity", "Tråd startad");
					connected = true;
					while (socket.isConnected()) {
						Log.i("ClientActivity", "Väntar på meddelande från servern");
						try {
						Log.d("ClientActivity","" + new BufferedReader(_InPut).readLine());						
						Log.i("ClientActivity", "Har mottaigt ett meddelande från servern: " );
						//Log.d("ClientActivity", "Kör!");
					} catch (Exception e) {
								Log.e("ClientActivity", "S: Error " + e.getMessage(),e);
						}
					}
					socket.close();
				} catch (Exception e) {
					Log.e("ClientActivity", "C: Error " + e.getMessage(), e);
				
				}
			}
		}
		


Thanks

This post has been edited by EndLessMind: 27 November 2011 - 04:47 PM

Was This Post Helpful? 0
  • +
  • -

#6 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 276
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 05:56 PM

What is your code for sending the response from the server?
Was This Post Helpful? 0
  • +
  • -

#7 EndLessMind  Icon User is offline

  • These are the droids you're looking for
  • member icon

Reputation: 193
  • View blog
  • Posts: 1,097
  • Joined: 13-March 09

Re: Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 06:54 PM

That would be
if (textBox2.Text.Length != 0)
			{
				char[] charArray = textBox2.Text.ToCharArray(0,textBox2.Text.Length);
				dataToSend = new byte[textBox2.Text.Length];
				for (int charCount = 0; 
					charCount < textBox2.Text.Length;
					charCount++)
				{
					dataToSend[charCount] = (byte)charArray[charCount];
				}
			}
			else
			{
				dataToSend = new byte[]{(byte)'e',(byte)'m',(byte)'p',(byte)'t',(byte)'y'};
			}
			tcp.GetStream().Write(dataToSend,0,dataToSend.Length);
			textBox2.Text = "";

:)
Was This Post Helpful? 0
  • +
  • -

#8 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 276
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 07:13 PM

Is that java your are using for your server?
It looks like you need to append a new line char to the end of your data before you send it.
Was This Post Helpful? 1
  • +
  • -

#9 EndLessMind  Icon User is offline

  • These are the droids you're looking for
  • member icon

Reputation: 193
  • View blog
  • Posts: 1,097
  • Joined: 13-March 09

Re: Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 07:16 PM

No, my server is in C# and runs on my PC.
But there is not problem with sending the data to my Android app, the problem is then i try to display the string correctly when the phone has received it.
But i'll try adding a new-line as the end.

Edit:
It worked :)
And yes, it make sens.
i use Buffered(stream).readLine()
That reads all the line, but if there are only one line, then thats going to give you some trouble :)

This post has been edited by EndLessMind: 27 November 2011 - 07:23 PM

Was This Post Helpful? 0
  • +
  • -

#10 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 276
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: Socket client. Sends message only when exiting the app

Posted 27 November 2011 - 07:27 PM

Using line = rd.readLine() will read the input steam and return the data when it reads the "\n" char.
if your going to use rd.read() you should parse it to a string like so:
 String data = new String(rd.read());


Edit: didnt see ur edit when i posted my reply. Im glad it workd :D

This post has been edited by H3R3T1C: 27 November 2011 - 07:28 PM

Was This Post Helpful? 0
  • +
  • -

#11 arazi77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 11-January 12

Re: Socket client. Sends message only when exiting the app

Posted 11 January 2012 - 08:20 AM

I still got "socket.Close();"

here my code.. Sending Part
---------------------------
public boolean sendMessage(String message){
try {
Log.i("ClientActivity", message);
_OutPut.writeBytes(message + "\n");
_OutPut.flush();
_OutPut.close();
Log.i("ClientActivity", "Meddelande ska vara skickat!");
return true;
}catch (Exception e){
Log.e("ClientActivity", e.getMessage());
_listener.interrupt();
}
return false;
}

and also i still stuck on receive data from server... can I get you full source code?
Was This Post Helpful? 0
  • +
  • -

#12 EndLessMind  Icon User is offline

  • These are the droids you're looking for
  • member icon

Reputation: 193
  • View blog
  • Posts: 1,097
  • Joined: 13-March 09

Re: Socket client. Sends message only when exiting the app

Posted 11 January 2012 - 12:03 PM

we will work this out together.
What code do you have in the onCreate?
Was This Post Helpful? 0
  • +
  • -

#13 arazi77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 11-January 12

Re: Socket client. Sends message only when exiting the app

Posted 11 January 2012 - 07:31 PM

Ok this is the code

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);

serverIP = (EditText)findViewById(R.id.Server_ip);
ConnectComp = (Button)findViewById(R.id.btnConnect);
BtnSend = (Button)findViewById(R.id.btnSkicka);
BtnSend.setonclickListener(SendListner);
ConnectComp.setonclickListener(connectListener);
}

private onclickListener SendListner = new onclickListener() {
@Override
public void onclick(View v) {
sendMessage("Hej Server!");
}
};

private onclickListener connectListener = new onclickListener() {

@Override
public void onclick(View v) {
if(!connected) {
IpAddress = serverIP.getText().toString();

if(!IpAddress.equals("")) {
InetAddress serverAddr;
try {
serverAddr = InetAddress.getByName(IpAddress);
Log.d("ClientActivity","C: Ansluter...");
socket = new Socket(serverAddr, 3005);

_InPut = new DataInputStream(socket.getInputStream());

_OutPut = new DataOutputStream(socket.getOutputStream());
_listener = new Thread(new ClientThread());
Toast.makeText(getBaseContext(), "M1", 1000).show();
_listener.start();

Log.d("ClientActivity", "C: Ansluten.");
Toast.makeText(getBaseContext(), "M2", 1000).show();
} catch (Exception e) {
Log.e("ClientActivity", e.getMessage());
}
}
}
}
};

public class ClientThread implements Runnable {
public void run() {
try {
Log.d("ClientActivity", "Tråd startad");
connected = true;

while (socket.isConnected()) {

Log.i("ClientActivity", "Väntar på meddelande från servern");
try {

Log.d("ClientActivity","Data : " + _InPut.read());
//Log.d("ClientActivity","Data : " + sentence);



} catch (Exception e) {
Log.e("ClientActivity", "S: Error " + e.getMessage(),e);
}
}


socket.close();

} catch (Exception e) {
Log.e("ClientActivity", "C: Error " + e.getMessage(), e);

}
}
}
Was This Post Helpful? 0
  • +
  • -

#14 EndLessMind  Icon User is offline

  • These are the droids you're looking for
  • member icon

Reputation: 193
  • View blog
  • Posts: 1,097
  • Joined: 13-March 09

Re: Socket client. Sends message only when exiting the app

Posted 11 January 2012 - 09:25 PM

Sorry, i wont read that.
Please use the code-tags: [ code ] *your code* [ /code ] (without spaces between brackets)

Edit the post and add the tags, or make a new post with the code within the tags.

This post has been edited by EndLessMind: 11 January 2012 - 09:26 PM

Was This Post Helpful? 1
  • +
  • -

#15 arazi77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 11-January 12

Re: Socket client. Sends message only when exiting the app

Posted 11 January 2012 - 09:46 PM

        [b][u]This for OnCreate[/u][/b]

        @Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main2);
		
		serverIP = (EditText)findViewById(R.id.Server_ip);
		ConnectComp = (Button)findViewById(R.id.btnConnect);
		BtnSend = (Button)findViewById(R.id.btnSkicka);
		BtnSend.setonclickListener(SendListner);
		ConnectComp.setonclickListener(connectListener);
	}




        [b][u]This for onclickListener SendListner[/u][/b]

        private onclickListener SendListner = new onclickListener() {
		@Override
		public void onclick(View v) {
			sendMessage("Hej Server!");			
		}
	};




        [b][u]This for onclickListener connectListener[/u][/b]

        private onclickListener connectListener = new onclickListener() {
		
		@Override
		public void onclick(View v) {
			if(!connected) {
				IpAddress = serverIP.getText().toString();
				
				if(!IpAddress.equals("")) {
					InetAddress serverAddr;
					try {
						serverAddr = InetAddress.getByName(IpAddress);
						
						socket = new Socket(serverAddr, 3005);
						Log.d("ClientActivity","Server IP: " + serverAddr);
						
						_InPut = new DataInputStream(socket.getInputStream());	
						_OutPut = new DataOutputStream(socket.getOutputStream());
						
						_listener = new Thread(new ClientThread());
						Toast.makeText(getBaseContext(), "M1", 1000).show();
						_listener.start();
						
						Log.d("ClientActivity", "C: Ansluten.");
						Toast.makeText(getBaseContext(), "M2", 1000).show();
					} catch (Exception e) {
						Log.e("ClientActivity", e.getMessage());
					}
				}
			}
		}
		};




        [b][u]This for ClientThread[/u][/b]

        public class ClientThread implements Runnable {
			
	    public void run() {
								
	        try {
		    Log.d("ClientActivity", "Tråd startad");
		    connected = true;
					
		    while (socket.isConnected()) {
						
		    //Log.i("ClientActivity", "Väntar på meddelande från servern");
	            try {											      
                         Log.d("ClientActivity","Data : " +  
                     _InPut.read());     											
		    } catch (Exception e) {
			Log.e("ClientActivity", "S: Error " + e.getMessage(),e);
		      }
	         }
					
		_InPut.close();
		socket.close();
					
		} catch (Exception e) {
		      Log.e("ClientActivity", "C: Error " + e.getMessage(), e);
		}
			}
		}



Was This Post Helpful? 0
  • +
  • -

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »