The docs say AsyncTask is designed to handle short operations(few seconds maximum) and states that Java classes like FutureTask are better for operations that last long. So I tried to send my location updates to the server using FutureTask but I am getting NetworkOnMainThreadException. I don't want to use AsyncTask because I wanted to keep the http connection open until the updates are cancelled. Here is my code:
SendLocation updates = new SendLocation(idt, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
FutureTask ft = new FutureTask<String>(updates);
boolean b = ft.cancel(false);
ft.run();
class SendLocation implements Callable<String> {
String t, la, lo;
public SendLocation(String a, String b, String c){
this.t = a;
this.la = b;
this.lo = c;
}
public String call() {
sendUpdates(token, la, lo);
return "Task Done";
}
public void sendUpdates(String a, String b, String c){
HttpURLConnection urlConn = null;
try {
try {
URL url;
//HttpURLConnection urlConn;
url = new URL(remote + "driver.php");
urlConn = (HttpURLConnection) url.openConnection();
System.setProperty("http.keepAlive", "true");
//urlConn.setDoInput(true); //this is for get request
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
urlConn.connect();
try {
//Create JSONObject here
JSONObject json = new JSONObject();
json.put("drt", a);
json.put("drlat", b);
json.put("drlon", c);
String postData = json.toString();
// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
os.flush();
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg = "";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line;
}
Log.i("msg=", "" + msg);
} catch (JSONException jsonex) {
jsonex.printStackTrace();
Log.e("jsnExce", jsonex.toString());
}
} catch (MalformedURLException muex) {
// TODO Auto-generated catch block
muex.printStackTrace();
} catch (IOException ioex) {
ioex.printStackTrace();
try { //if there is IOException clean the connection and clear it for reuse(works if the stream is not too long)
int respCode = urlConn.getResponseCode();
InputStream es = urlConn.getErrorStream();
byte[] buffer = null;
int ret = 0;
// read the response body
while ((ret = es.read(buffer)) > 0) {
Log.e("streamingError", String.valueOf(respCode) + String.valueOf(ret));
}
// close the errorstream
es.close();
} catch(IOException ex) {
// deal with the exception
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "There is error in this code " + String.valueOf(e));
}
}
}
Doesn't it get executed in a worker thread? If the answer is no why does the docs say that it is an alternative to AsyncTask?
Your code must not be in the void run() method. This is where the asynchronous code is ran.
This is the error caused after runnung the code
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.lang.Thread.run(Thread.java:841)
03-13 16:43:00.901: E/AndroidRuntime(18994): Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 56: http://suprabha.orgfree.com/ecg/temp.php?name=10&temper= 31,w=t
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.net.URI.create(URI.java:727)
03-13 16:43:00.901: E/AndroidRuntime(18994): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
03-13 16:43:00.901: E/AndroidRuntime(18994): at com.example.mobilehealthcare.Temperature$DownloadWebPageTask.doInBackground(Temperature.java:271)
java file
package com.example.mobilehealthcare;
public class Temperature extends Activity {
private static final String TAG = "bluetooth2";
Button btnOn, btnOff;
TextView txtArduino;
Handler h;
private GraphView mGraph;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
// private static String address = "00:12:09:29:42:57";
// private static String address = "00:15:83:15:A3:10";
// private static String address = "20:13:07:12:04:17";
String sdop = "";
String pd = "";
String s1,sa,s1nom,sakom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temperature);
SharedPreferences pre = getSharedPreferences("pref", 0);
s1 = pre.getString("savedDatasd", "10");
s1nom = pre.getString("savedDatad", "10");
mGraph = (GraphView)findViewById(R.id.grap);
txtArduino = (TextView)findViewById(R.id.texView1);
mGraph.setMaxValue(1024);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
// int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
int endOfLineIndex = sb.indexOf("/");
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
Toast.makeText(getApplicationContext(), "received message"+"----"+sbprint, 30).show();
sb.delete(0, sb.length()); // and clear
txtArduino.setText(sbprint); // update TextView
// final int s = Integer.parseInt(sbprint);
// mGraph.addDataPoint(s);
sdop+= txtArduino.getText().toString()+",";
}
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
public void tyre(View v)
{
mConnectedThread.write("t");
Toast.makeText(this, "waid for values to be received", Toast.LENGTH_SHORT).show();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(s1);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
SharedPreferences preferences = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = preferences.edit();
//"savedData" is the key that we will use in onCreate to get the saved data
//mDataString is the string we want to save
// editor.putString("savedDatasd", sa);
// editor.putString("savedDatad", sakom);
// commit the edits
editor.commit();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
public void bus(View v)
{
Intent jkl = new Intent(this,Select.class);
startActivity(jkl);
finish();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
//msg.setText(result);
if (result.contains("success")) {
Toast.makeText(getApplicationContext(), "Values are isent to Doctor", 30).show();
}else{Toast.makeText(getApplicationContext(), "Values are not sent to Doctor", 30).show();}
}
}
public void sav(View v)
{
String e = "t";
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://suprabha.orgfree.com/ecg/temp.php?name="+s1nom+"&temper="+sdop+"w="+e });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.temperature, menu);
return true;
}
}
Is it due to the php code?
or is the error in this java file.?
Which charater should be changed?
The error is in download web page task.
Edit:
This is the other code with same concept:
this works without error
public class Register extends Activity {
EditText a,b,c,d,e,f,g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
a = (EditText) findViewById(R.id.editname1);
b = (EditText) findViewById(R.id.editpas1);
c = (EditText) findViewById(R.id.age);
d = (EditText) findViewById(R.id.editph1);
e = (EditText) findViewById(R.id.editadd1);
f = (EditText) findViewById(R.id.editem1);
g = (EditText) findViewById(R.id.dph);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
//msg.setText(result);
if (result.contains("success")) {
Intent i2 = new Intent(getApplicationContext(), Login.class);
//i.putExtra("id",na);
startActivity(i2);
}else{Toast.makeText(getApplicationContext(), result, 30).show();}
}
}
public void insert(View v)
{
String h,i,j,k,l,m,n;
h = a.getText().toString();
i = b.getText().toString();
j = c.getText().toString();
k = d.getText().toString();
l = e.getText().toString();
m = f.getText().toString();
n = g.getText().toString();
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://suprabha.orgfree.com/ecg/regis.php?name="+h+"&pass="+i+"&age="+j+"&ph="+k+"&addr="+l+"&em="+m+"&docph="+n });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register, menu);
return true;
}
}
seems to me that the query url "__http://suprabha.orgfree.com/ecg/temp.php?name=10&temper= 31,w=t" is where the program is encountering problem.
the 56th character is "=" which shouldnt be unexpected. However the spaces before the "31" in the string, can those be a point of concern?
If the spaces are not required as per your design, i would suggest you to remove and try it. If, they are however required, i would suggest escaping it before using the same.
Hope it helps.
note: ignore the undescores before the url. did that to prevent hyperlinking.
Problem are the blank spaces after the = symbol. You can avoid this simply with String:trimm(), but won't solve other problems, so, to avoid this, with URL's use java.net.URLEncoder to fit your needed enconding, for example:
URLEncoder.encode(url, "UTF-8");
In your case:
HttpGet httpGet = new HttpGet(URLEncoder.encode(url, "UTF-8"));
float totalKm = Contsants.jobEndKm-Contsants.jobStartKm ;
jcTotalKms.setText(String.format("%.2f",totalKm));
//jcTotalKms.setText(Float.toString((float) (totalKm/16.0)));
//finding total fare here
//int value=100;
if (totalKm<Contsants.minDist)
{
jcWaitingFare.setText("0");
float totalfare=Contsants.minFare;
jcTotalFare.setText(String.format("%.2f",(totalfare)));
Contsants.jobTotalKm= totalKm;
Contsants.jobTotalFare=totalfare;
}
else
{
jcWaitingFare.setText(Integer.toString((Contsants.cont_WaitingTimeInSec/60)*1));
float totalfare= Contsants.minFare+ ((totalKm-Contsants.minDist) *Contsants.rupeeKm) +(Contsants.cont_WaitingTimeInSec/60)*1;
jcTotalFare.setText(String.format("%.2f",(totalfare)));
Contsants.jobTotalKm= totalKm;
Contsants.jobTotalFare=totalfare;
}
tcpsocket class
public class tcpSocket extends Thread{
static boolean startSocket=false;
public static final String SERVERIP = "ip address here"; //your computer IP address
public static final int SERVERPORT = 8900;
private static boolean mRun = false;
public static Socket socket;
public static OnMessageReceived mMessageListener;
public static OnMessageReceived getmMessageListener() {
return mMessageListener;
}
public static void setmMessageListener(OnMessageReceived mMessageListener) {
tcpSocket.mMessageListener = mMessageListener;
}
public tcpSocket()
{
}
#Override
public void run(){
//some long operation
startSocket=true;
while(startSocket)
{
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.d("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
Log.d("TCP Client", "C: Sent.");
Log.d("TCP Client", "C: Done.");
final OutputStream out =socket.getOutputStream();
writeResponse(out, "$0001~01~"+Contsants.Cont_IMEINo+"~Version#");
//in this while the client listens for the messages sent by the server
final InputStream in = socket.getInputStream();
while(!mRun)
{
if (!(in.available() > 0)) {
goSleep(2000);
continue;
}
processClient(in);
}
}catch (Exception e) {
// TODO: handle exception
}finally{
socket.close();
}
} catch (Exception e) {
Log.d("tcp error",e.toString());
// TODO: handle exception
}
}
}
private void goSleep(final long milliSec) {
try {
Thread.sleep(milliSec);
} catch (final InterruptedException e) {
Log.e("server conn Thread ","Sleeping client interrupted" + e);
}
}
private void processClient(final InputStream in) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
final char[] cbuf = new char[1024];
final int length = reader.read(cbuf);
if (length <= 0) {
Log.d("d","No data read from client.");
return;
}
cbuf[length] = '#';
String packet = new String(cbuf, 0, length + 1);
if (!packet.startsWith("$") && !packet.contains("#")) {
Log.d("d","Invalid packet recieved: " + packet);
return;
}
try
{
if(!packet.contains("$0002") && !packet.contains("$0423"))
{
final String [] packetDo=packet.split("\\~");
writeResponse(socket.getOutputStream(), "$102~"+packetDo[1]+"~"+Contsants.Cont_IMEINo+"#");
}
Log.d("d","Recived packet is :"+packet);
Message msg = new Message();
Bundle b = new Bundle();
b.putString("ServerMsg", packet);
msg.setData(b);
// send message to the handler with the current message handler
mHandler.sendMessage(msg);
}catch (Exception e) {
// TODO: handle exception
Log.e("TCP", "p: Error", e);
}
}
Handler mHandler =new Handler(){
#Override
public void handleMessage(Message message){
//update UI
Bundle b = message.getData();
final String data =b.getString("ServerMsg");
mMessageListener.messageReceived(data);
}
};
/*public class MyAsync extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
String response = null;
return SendMessage(response);
}
}
public static boolean SendMessage(final String response) {
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out, response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun = true;
return false;
}
return true;
}
*/
public static boolean SendMessage(final String response)
{
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out,response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun=true;
return false;
}
return true;
}
private static void writeResponse(final OutputStream out, final String response) throws IOException {
// logger.info("Sending response to client: " + response);
out.write(response.getBytes());
out.flush();
}
}
here is my code for calculating distance and fare together when the condition exceeds minimum(minDist) kilometer. But while checking this application in real device it hangs up after two kilometer. Because after two kilometer it goes to else condition part. i don't know how to solve this issue.
I was previously using HttpClient and BasicNameValuePairs, for some reason i have to shift to HttpUrlConnection.
Hence this code, to make a HttpPost request with certain parameters:
public class MConnections {
static String BaseURL = "http://www.xxxxxxxxx.com";
static String charset = "UTF-8";
private static String result;
private static StringBuilder sb;
private static List<String> cookies = new ArrayList<String>();
public static String PostData(String url, String sa[][]) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(BaseURL + url)
.openConnection();
} catch (MalformedURLException e1) {
} catch (IOException e1) {
}
cookies = connection.getHeaderFields().get("Set-Cookie");
try{
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
}catch (Exception e) {
//Here i get Exception that "java.lang.IllegalStateException: Already connected"
}
OutputStream output = null;
String query = "";
int n = sa.length;
for (int i = 0; i < n; i++) {
try {
query = query + sa[i][0] + "="
+ URLEncoder.encode(sa[i][1], "UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} catch (Exception e) {
//Here i get Exception that "android: java.net.protocolException: Does not support output"
} finally {
if (output != null)
try {
output.close();
} catch (IOException e) {
}
}
InputStream response = null;
try {
response = connection.getInputStream();
} catch (IOException e) {
//Here i get Exception that "java.io.IOException: BufferedInputStream is closed"
} finally {
//But i am closing it here
connection.disconnect();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
response, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine());
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append("\n" + line);
}
response.close();
result = sb.toString();
} catch (Exception e) {
}
return result;
}
}
But i get such Exceptions as commented in the code.
Actually i am calling MConnections.PostData() twice from my Activity using a AsyncTask. This might cause the Exception: Already Connected but i am using connection.disconnect. But why am i still getting that Exception?
Am i using it the wrong way?
Thank You
For the protocol exception, try adding the following before you call getOutputStream():
connection.setDoOutput(true);
Discovered this answer thanks to Brian Roach's answer here: https://stackoverflow.com/a/14026377/387781
Side note: I was having this issue on my HTC Thunderbolt running Gingerbread, but not on my Nexus 4 running Jelly Bean.
The server should send a message "Hello :: enter QUIT to exit" to the client, then the client types in any text and the server echos back the client's text adding "From server: " before their message.
But there seems to be a mix up in the order and I can't seem to find where! I've been on this all day!
This is the Server's code:
import java.net.*;
public class Server {
public static void main(String[] args) {
int nreq = 1;
try
{
ServerSocket sock = new ServerSocket (8080);
for (;;)
{
Socket newsock = sock.accept();
System.out.println("Creating thread ...");
Thread t = new ThreadHandler(newsock,nreq);
t.start();
}
}
catch (Exception e)
{
System.out.println("IO error " + e);
}
System.out.println("End!");
}
}
ThreadHandler code:
import java.io.*;
import java.net.*;
class ThreadHandler extends Thread {
Socket newsock;
int n;
ThreadHandler(Socket s, int v) {
newsock = s;
n = v;
}
// #SuppressWarnings("deprecation")
public void run() {
try {
PrintWriter outp = new PrintWriter(newsock.getOutputStream(), true);
BufferedReader inp = new BufferedReader(new InputStreamReader(
newsock.getInputStream()));
outp.println("Hello :: enter QUIT to exit");
boolean more_data = true;
String line;
while (more_data) {
line = inp.readLine();
if (line == null) {
more_data = false;
} else {
outp.println("From server: " + line + "\n");
if (line.trim().equals("QUIT"))
more_data = false;
}
}
newsock.close();
} catch (Exception e) {
System.out.println("IO error " + e);
}
}
}
And the Client code:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
// #SuppressWarnings("deprecation")
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
try {
Socket s = new Socket("localhost", 8080);
PrintWriter outp = new PrintWriter(s.getOutputStream(), true);
BufferedReader inp = new BufferedReader(new InputStreamReader(
s.getInputStream()));
boolean more_data = true;
System.out.println("Established connection");
String line;
while (more_data) {
line = inp.readLine();
String userInput = scanner.nextLine();
outp.println(userInput);
if (line == null) {
more_data = false;
} else
System.out.println(line);
}
System.out.println("end of while");
} catch (Exception e) {
System.out.println("IO error " + e);
}
}
}
I'm testing it out so after I'm going to make the client an Android phone - if that's possible -
Update:
I've changed the server's code to:
outp.println("Hello :: enter QUIT to exit \n");
boolean more_data = true;
String line;
while (more_data) {
line = inp.readLine();
System.out.println("Message '" + line + "' echoed back to client.");// !!
if (line == null) {
System.out.println("line = null");
more_data = false;
} else {
outp.println("From server: " + line + ". \n");
if (line.trim().equals("QUIT"))
more_data = false;
}
}
newsock.close();
System.out.println("Disconnected from client number: " + n);
and added "\n" at the end of the Hello message as Luis Miguel Serrano suggested, And changed the Client's side as below:
boolean more_data = true;
System.out.println("Established connection");
String line;// = inp.readLine();
while (more_data) {
line = inp.readLine();
System.out.println(line);
if (line == null) {
// nothing read
more_data = false;
} else
line = inp.readLine();
System.out.println(line);
String userInput = scanner.nextLine();
if (userInput.trim() == "QUIT") {
s.close();
System.out.println("Disconnected from server.");
more_data = false;
} else
outp.println(userInput);
}
System.out.println("end of while");
And it works fine now.
If anyone could suggest me some Android client-java server tutorials would appreciate it.
In sequence of your comment, it could be a flushing issue. Try adding the following line:
outp.flush();
after:
outp.println("Hello :: enter QUIT to exit");
When you write to a stream, sometimes the things you write are kept in a buffer. If you want to make sure that buffer is emptied and the string is actually sent, you need to call the flush() method.
Update
Also, add "\n" to the end of your Hello welcome message from the server. I think that will make it work.