How to get multiple messages from server in android socket - android

I am implementing socket programming in android. I am successfully getting data from client and displaying it to the server.
The asynctask is as follows:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
The above code gets data from server and write it to the text view. I want to use the same socket to get data multiple times from server, unless a particular button is clicked. But, in doInBackground, we can't use any ui component. I want to change the following component, so that I can recieve multiple data from the server:
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
I tried to use
onProgressUpdate
but it didn't work either. Please help me to solve this.
Edit 1: the client's main activity :
package com.example.shiza.client;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "CLIENT_MESSAGE";
EditText ip_address;
EditText port_number;
EditText message_client;
Button button_send;
Button button_cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connect(View view) {
// ip_address = (EditText) findViewById(R.id.ip_address);
// ip_address.setText("192.168.9.100");
// port_number = (EditText) findViewById(R.id.port_number);
// port_number.setText("8080");
message_client = (EditText) findViewById(R.id.message_client);
button_send = (Button)findViewById(R.id.button_send);
button_cancel = (Button)findViewById(R.id.button_cancel);
Log.d(TAG, "connecting to the server.");
// new ConnectToServer(ip_address.getText().toString(), port_number.getText().toString(), message_client,button_send,button_cancel).execute();
new ConnectToServer("192.168.9.100","8080", message_client,button_send,button_cancel).execute();
}
}
class ConnectToServer extends AsyncTask<Void, DataOutputStream, Void> {
private static final String TAG = "CLIENT_MESSAGE";
String ip_address;
int port_number;
EditText message_client;
Button button_send;
Button button_cancel;
boolean send = false;
boolean cancel = false;
public ConnectToServer(String ip_address, String port_number, EditText message_client,Button button_send,Button button_cancel) {
this.ip_address = ip_address;
this.port_number = Integer.parseInt(port_number);
this.message_client = message_client;
this.button_cancel = button_cancel;
this.button_send = button_send;
}
#Override
protected Void doInBackground(Void... params) {
try {
Socket socket = new Socket(ip_address, port_number);
if (LoggerConfig.TAG) {
Log.d(TAG, "the socket is created at " + ip_address);
}
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
while (!cancel )
publishProgress(output);
// output.writeUTF("Hello from string");
if (LoggerConfig.TAG) {
Log.d(TAG, "I have written and closed the loop.");
}
socket.close();
} catch (IOException e) {
if (LoggerConfig.TAG) {
Log.d(TAG, "Could not connect.");
}
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(DataOutputStream... values) {
super.onProgressUpdate(values);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
send = true;
}
});
button_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel = true;
}
});
Log.d(TAG, "I am in onProgressUpdate");
if ( send )
{
try {
values[0].writeUTF(message_client.getText().toString());
Log.d(TAG, "I am in onProgressUpdate try.");
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "I am in onProgressUpdate catch.");
}
send = false;
}
}
}
The server's main activity:
package com.example.shiza.server;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
TextView ip_address;
TextView client_message;
TextView server_status;
TextView show_client_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip_address = (TextView) findViewById(R.id.ip_address);
client_message = (TextView) findViewById(R.id.get_client_message);
server_status = (TextView) findViewById(R.id.server_status);
show_client_message = (TextView) findViewById(R.id.show_client_message);
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
ip_address.setText(ip);
// Making a server socket here
}
public void startServer(View view) {
GetFromClient getFromClient = new GetFromClient(this,server_status,show_client_message);
getFromClient.execute();
}
}
class GetFromClient extends AsyncTask<Void, String, Void> {
Context context;
TextView server_status;
TextView show_client_message;
String TAG = "SERVER_MESSAGE";
String inputFromClient = null;
public GetFromClient(Context context,TextView server_status,TextView show_client_message) {
this.context = context;
this.server_status = server_status;
this.show_client_message = show_client_message;
}
#Override
protected Void doInBackground(Void... params) {
Socket socket;
try {
ServerSocket serverSocket = new ServerSocket(8080);
Log.d(TAG, "Server Socket is starting....");
// server_status.setText("The server is running");
publishProgress("okay");
socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
// Calling the second background task for handling input from server
// Log.d(TAG, "Server Socket is started....");
do
{
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
inputFromClient = input.readUTF();
publishProgress(inputFromClient);
}
while ( inputFromClient != "bye" );
// publishProgress(2);
socket.close();
} catch (IOException e) {
Log.d(TAG, "I am in catch.");
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d(TAG, "I am in onProgress update.");
if ( values[0].equals("okay") )
{
server_status.setText("Server has been started");
server_status.setTextColor(context.getResources().getColor(R.color.green));
}
else
{
show_client_message.setText(values[0]);
}
}
protected void onPostExecute(Void inputFromClient)
{
Log.d(TAG, "I am in onPostExecute.");
server_status.setText("Server is not running");
server_status.setTextColor(context.getResources().getColor(R.color.red));
}
}
I am able to do the messaging but the following loop blocks everything:
do
{
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
inputFromClient = input.readUTF();
publishProgress(inputFromClient);
}
while ( inputFromClient != "bye" );

You can update your TextView in the doInBackground method using RunUiThread. After receiving the data from server just call
runOnUiThread(new Runnable() {
#Override
public void run() {
//here you update the views
}
});

Related

Android Client sends Objects to server and server does receive them but client can't read response

I am sending a Collection(NetworkObject) via ObjectInput and Outputstreams to a server and he receives them without a problem, but he can't read the response which should be a string(also object now for testing). But the app keeps telling me the socket is closed.
Thanks in advance.
My whole Activity
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import com.example.cl.BasicActivity;
import com.example.cl.data.NetworkObject;
import com.example.cl.R;
import com.example.cl.data.Produkt;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import static java.lang.Thread.sleep;
public class ServerHandler extends BasicActivity implements View.OnClickListener {
public static final int SERVERPORT = 26000;
public static final String SERVER_IP = "192.168.1.2";
//public static final String SERVER_IP = "192.168.0.206";
private ClientThread clientThread;
private Thread thread;
private LinearLayout msgList;
private Handler handler;
private int clientTextColor;
private EditText edMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
setTitle("Client");
clientTextColor = ContextCompat.getColor(this, R.color.green);
handler = new Handler();
msgList = findViewById(R.id.msgList);
edMessage = findViewById(R.id.edMessage);
}
public TextView createLine(String message, int color) {
if (null == message || message.trim().isEmpty()) {
message = "<Empty Message>";
}
TextView tv = new TextView(this);
tv.setTextColor(color);
tv.setText(message );
tv.setTextSize(20);
tv.setPadding(0, 5, 0, 0);
return tv;
}
public void showMessage(final String message, final int color) {
handler.post(new Runnable() {
#Override
public void run() {
msgList.addView(createLine(message, color));
}
});
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.connect_server) {
msgList.removeAllViews();
showMessage("Connecting to Server...", clientTextColor);
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
return;
}
if (view.getId() == R.id.send_data) {
String clientMessage = edMessage.getText().toString().trim();
showMessage(clientMessage, Color.BLUE);
if (null != clientThread) {
clientThread.sendMessage(clientMessage);
}
}
if (view.getId() == R.id.send_elem) {
if (null != clientThread) {
clientThread.sendElem(/*bestellung*/);
}
}
}
class ClientThread implements Runnable {
private Socket socket;
//private BufferedReader input;
private ObjectInputStream ois;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
//sleep(250);
if (socket != null)
showMessage("Connected to Server!", clientTextColor);
while (!Thread.currentThread().isInterrupted()) {
//this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
//ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
//String message = input.readLine();
NetworkObject networkObject = (NetworkObject) ois.readObject();
/*
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
showMessage(message, Color.RED);
break;
}
*/
showMessage("Server: " + networkObject, clientTextColor);
// showMessage("Server: " + message, clientTextColor);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException | ClassNotFoundException e1) {
e1.printStackTrace();
}
}
void sendMessage(final String message) {
new Thread(new Runnable() {
#Override
public void run() {
try(ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));) {
if (null != socket) {
oos.writeUTF(message);
oos.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
void sendElem(/*NetworkObject networkObject*/) {
new Thread(new Runnable() {
#Override
public void run() {
try(ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));) {
if (null != socket) {
Produkt produkt = new Produkt("Bier","Zipfer",16,3.50,1,true);
List<Object> produktList = new LinkedList<>();
produktList.add(produkt);
produktList.add(produkt);
NetworkObject networkObject = new NetworkObject("order",46020849,1,produktList);
showMessage(networkObject.toString(), Color.BLUE);
oos.writeObject(networkObject);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
The thread in the Clienthandler which should read it also contains the sending methods but they should work.
private Socket socket;
//private BufferedReader input;
private ObjectInputStream ois;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
//sleep(250);
if (socket != null)
showMessage("Connected to Server!", clientTextColor);
while (!Thread.currentThread().isInterrupted()) {
//this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
//ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
//String message = input.readLine();
NetworkObject networkObject = (NetworkObject) ois.readObject();
/*
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
showMessage(message, Color.RED);
break;
}
*/
showMessage("Server: " + networkObject, clientTextColor);
// showMessage("Server: " + message, clientTextColor);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException | ClassNotFoundException e1) {
e1.printStackTrace();
}
}
The error I get
W/System.err: java.net.SocketException: Socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:119)
at java.net.SocketInputStream.read(SocketInputStream.java:176)
at java.net.SocketInputStream.read(SocketInputStream.java:144)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:248)
W/System.err: at java.io.BufferedInputStream.read1(BufferedInputStream.java:288)
at java.io.BufferedInputStream.read(BufferedInputStream.java:347)
at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2454)
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2470)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2947)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:858)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:353)
at com.example.cl.serverKom.ServerHandler$ClientThread.run(ServerHandler.java:131)
at java.lang.Thread.run(Thread.java:919)

how can I run to background process at once

I' working on an app which among other things preforms a port scan. My problem is that I'm trying to implement a progress bar as the scan takes place. Right now I use AsynTask to perform the scan. But how can I update the progress bar while the scan is performing? Can I use the same AsynTask for both task or I need to implement a separate one. Any help appreciate!
PortScanActivity
package com.example.android.droidscanner;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Created by jlvaz on 3/7/2017.
*/
public class PortScanActivity extends AppCompatActivity{
String ipAddress;
ArrayList<String> openPorts;
ArrayAdapter<String> portAdapter;
int startPort = 0;
int endPort = 1023;
TextView statusMsg;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan_list);
Intent portIntent = getIntent();
ipAddress = portIntent.getStringExtra("host");
statusMsg = (TextView) findViewById(R.id.status_msg);
//setting the adapter
ListView portList = (ListView) findViewById(R.id.scan_list);
openPorts = new ArrayList<>();
portAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, openPorts);
portList.setAdapter(portAdapter);
//scanning ports
PortScanTask portScan = new PortScanActivity.PortScanTask();
portScan.execute();
}
private class PortScanTask extends AsyncTask<Void, String, Void> {
int timeOut = 1000; //for how long try connection in ms
#Override
protected void onPreExecute() {
openPorts.clear();
statusMsg.setText("Scanning " + ipAddress + " ports..");
}
#Override
protected Void doInBackground(Void... params) {
for (int i = startPort; i <= endPort; i++) {
try {
//establishing connection to every port
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(ipAddress, i);
socket.connect(address, timeOut);
Log.v("Connecting to: ", ipAddress + i);
if (socket.isConnected()) {
socket.close();
publishProgress(ipAddress + ": " + i);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (ConnectException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
openPorts.add(values[0]);
portAdapter.notifyDataSetInvalidated();
Toast.makeText(getApplicationContext(), values[0].toString() + " open!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(Void aVoid) {
statusMsg.setText("Scan Complete!");
}
}
}
On progress update pass your custom class object which contains both, the string and the progress integer.
class ProgressStep {
int progress;
String address;
}
private class PortScanTask extends AsyncTask<Void, ProgressStep, Void> {
int timeOut = 1000; //for how long try connection in ms
#Override
protected void onPreExecute() {
openPorts.clear();
statusMsg.setText("Scanning " + ipAddress + " ports..");
}
#Override
protected Void doInBackground(Void... params) {
for (int i = startPort; i <= endPort; i++) {
try {
//establishing connection to every port
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(ipAddress, i);
socket.connect(address, timeOut);
Log.v("Connecting to: ", ipAddress + i);
int progress = count_your_progress;
ProgressStep step = new ProgressStep();
step.progress = progress;
if (socket.isConnected()) {
socket.close();
String address = ipAddress + ": " + i;
step.address = address;
}
publishProgress(step);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (ConnectException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(ProgressStep... values) {
ProgressStep step = values[0];
if (step.address != null) {
openPorts.add(step.address);
portAdapter.notifyDataSetInvalidated();
Toast.makeText(getApplicationContext(), step.address + " open!", Toast.LENGTH_SHORT).show();
}
progressBar.setProgress(step.progress);
}
#Override
protected void onPostExecute(Void aVoid) {
statusMsg.setText("Scan Complete!");
}
}

how can I implement the onProgressUpdate method in this AsynTask Class

I'm working on a network scanner, and for that I'm sending the scan to the background using an AsyncTask class. But I'm having problems implementing the onProgressUpdate() method. I'm passing an ArrayList of type string to the TaskScanNetwork class. This array will have a list of all life host on network. Any help appreciated. Thanks
package com.example.android.droidscanner;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button btnRead;
Button btnScan;
TextView textResult;
ListView listViewNode;
ArrayList<Node> listNote;
ArrayList<String> listNetwork;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRead = (Button)findViewById(R.id.readhost);
btnScan = (Button) findViewById(R.id.readnet);
textResult = (TextView)findViewById(R.id.result);
listViewNode = (ListView)findViewById(R.id.nodelist);
listNote = new ArrayList<>();
listNetwork = new ArrayList<>();
//initidating adapter for host only
ArrayAdapter<Node> adapterHost = new ArrayAdapter<Node>(
MainActivity.this,
android.R.layout.simple_list_item_1,
listNote);
listViewNode.setAdapter(adapterHost);
//initiating adapter for network scan
ArrayAdapter<String> adapterNetwork = new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_list_item_1,
listNetwork);
listViewNode.setAdapter(adapterNetwork);
btnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskReadAddresses(listNote, listViewNode).execute();
}
});
btnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskScanNetwork(listNetwork, listViewNode).execute();
}
});
}
private class TaskReadAddresses extends AsyncTask<Void, Node, Void> {
ArrayList<Node> array;
ListView listView;
TaskReadAddresses(ArrayList<Node> array, ListView v){
listView = v;
this.array = array;
array.clear();
textResult.setText("querying...");
}
#Override
protected Void doInBackground(Void... params) {
readAddresses();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
textResult.setText("Done");
}
#Override
protected void onProgressUpdate(Node... values) {
listNote.add(values[0]);
((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();
}
private void readAddresses() {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ip = splitted[0];
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
Node thisNode = new Node(ip, mac);
publishProgress(thisNode);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* Asynctask to scan the network
* */
private class TaskScanNetwork extends AsyncTask<Void, ArrayList<String>, Void> {
String network;
ListView listView;
String lowBoundIp;
ArrayList<String> allNetwork;
TaskScanNetwork(ArrayList<String> array, ListView v){
listView = v;
allNetwork = array;
textResult.setText("Scanning...");
}
#Override
protected Void doInBackground(Void... params) {
scanNetwork();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
textResult.setText("Done");
}
#Override
protected void onProgressUpdate(ArrayList<String>... values) {
allNetwork.add(values);
((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();
}
private void scanNetwork() {
try {
InetAddress localHost = InetAddress.getLocalHost();
lowBoundIp = localHost.getHostAddress();
int lastDot = lowBoundIp.lastIndexOf(".");
String host = lowBoundIp.substring(0, lastDot);
Process ping;
for(int i = 1; i < 255; i++) {
host = host + "." + Integer.toString(i);
try {
ping = Runtime.getRuntime().exec("ping -n 1 " + host);
int returnVal = ping.waitFor();
if(returnVal == 0) {
publishProgress(allNetwork);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Make a string from a View element

I have two seekbars in my main activity but I can only use one of them at a time, so I need to retrieve a value seekbarx and seekbary, store either of them in a string variable to use it forward. I already used onProgressChange and onStopTrackingTouch but I guess it doesn't hold the value long enough.
This is what I had for the seekbars
package edu.itdurango.servocontrolyun;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity {
// TODO: adjust ARDUINO_IP_ADDRESS
public final String ARDUINO_IP_ADDRESS = "192.168.1.71"; //Dirección IP del Arduino Yun
public final String TAG = "ArduinoYun";
public String servo;
private SeekBar SeekBarX; //Barra de búsqueda del eje X
private SeekBar SeekBarY; //Barra de búsqueda del eje Y
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBarX = (SeekBar) findViewById(R.id.barraEjeX);
/*SeekBarX.setOnClickListener(new View.OnClickListener() {
public void onClick(View barraEjeX) {
servo = "servox/";
}
});*/
SeekBarX.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar barraEjeX) {
}
#Override
public void onStartTrackingTouch(SeekBar barraEjeX) {
}
#Override
public void onProgressChanged(SeekBar barraEjeX, int progressX,
boolean fromUser) {
servo = "servox/";
log("touching X bar. servo = " + servo);
QueueX.offer(progressX);
}
});
SeekBarY = (SeekBar) findViewById(R.id.barraEjeY);
/*SeekBarY.setOnClickListener(new View.OnClickListener() {
public void onClick(View barraEjeY) {
servo = "servoy/";
}
});*/
SeekBarY.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar barraEjeY) {
}
#Override
public void onStartTrackingTouch(SeekBar barraEjeY) {
}
#Override
public void onProgressChanged(SeekBar barraEjeY, int progressY,
boolean fromUser) {
servo = "servoy/";
log("touching Y bar. servo = " + servo);
QueueY.offer(progressY);
}
});
}
#Override
protected void onStart() {
mStop.set(false);
if(sNetworkThreadSend == null){
sNetworkThreadSend = new Thread(mNetworkRunnableSend);
sNetworkThreadSend.start();
}
super.onStart();
}
#Override
protected void onStop() {
mStop.set(true);
QueueX.clear();
QueueX.offer(-1);
QueueY.clear();
QueueY.offer(-1);
if(sNetworkThreadSend != null) sNetworkThreadSend.interrupt();
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void log(String s){
Log.d(">==< "+TAG+" >==<", s);
}
private ArrayBlockingQueue<Integer> QueueX = new ArrayBlockingQueue<Integer>(100);
private ArrayBlockingQueue<Integer> QueueY = new ArrayBlockingQueue<Integer>(100);
private AtomicBoolean mStop = new AtomicBoolean(false);
private static Thread sNetworkThreadSend = null;
private final Runnable mNetworkRunnableSend = new Runnable() {
#Override
public void run() {
log("starting network thread for sending");
String urlBase = "http://"+ARDUINO_IP_ADDRESS+"/arduino/"+servo;
String url;
try {
while(!mStop.get()){
int val;
if (servo == "servoy/"){
val = QueueY.take();
if(val >= 0){
HttpClient httpClient = new DefaultHttpClient();
url = urlBase.concat(String.valueOf(val));
log("executing httpClient request");
HttpResponse response = httpClient.execute(new HttpGet(url));
log(url);
}
}
if (servo == "servox/"){
val = QueueX.take();
if(val >= 0){
HttpClient httpClient = new DefaultHttpClient();
url = urlBase.concat(String.valueOf(val));
log("executing httpClient request");
HttpResponse response = httpClient.execute(new HttpGet(url));
log(url);
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
log("returning from network thread for sending");
sNetworkThreadSend = null;
}
};
private static Thread sNetworkThreadReceive = null;
private final Runnable mNetworkRunnableReceive = new Runnable() {
#Override
public void run() {
log("starting network thread for receiving");
String url = "http://"+ARDUINO_IP_ADDRESS+"/data/get/D9";
while(!mStop.get()){
try {
String string = readURL(url);
String value = "";
try {
JSONObject jsonMain = new JSONObject(string);
value = jsonMain.get("value").toString();
log("value = "+value);
} catch (Exception e) {
e.printStackTrace();
}
updateText(value);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log("returning from network thread for receiving");
sNetworkThreadReceive = null;
}
};
public void updateText(final String value){
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(value);
}
});
}
public String readURL(String value){
URL url;
StringBuilder builder = new StringBuilder();
try {
url = new URL(value);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
builder.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
It prints in the LogCat touching Y bar. servo = servoy/ but when I want to use the servo value it prints null.
How can I hold the value for this string?

Android Socket Fails

Heres my Server Code
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Threading;
public class SynchronousSocketListener
{
private const int portNum = 4444;
private static ArrayList ClientSockets;
private static bool ContinueReclaim = true;
private static Thread ThreadReclaim;
public static void StartListening()
{
ClientSockets = new ArrayList();
ThreadReclaim = new Thread(new ThreadStart(Reclaim));
ThreadReclaim.Start();
TcpListener listener = new TcpListener(portNum);
try
{
listener.Start();
int TestingCycle = 3;
int ClientNbr = 0;
// Start listening for connections.
Console.WriteLine("Waiting for a connection...");
while (TestingCycle > 0)
{
TcpClient handler = listener.AcceptTcpClient();
if (handler != null)
{
Console.WriteLine("Client#{0} accepted!", ++ClientNbr);
// An incoming connection needs to be processed.
lock (ClientSockets.SyncRoot)
{
int i = ClientSockets.Add(new ClientHandler(handler));
((ClientHandler)ClientSockets[i]).Start();
Console.WriteLine("Added sock {0}", i);
}
--TestingCycle;
}
else
break;
}
listener.Stop();
ContinueReclaim = false;
ThreadReclaim.Join();
foreach (Object Client in ClientSockets)
{
((ClientHandler)Client).Stop();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
private static void Reclaim()
{
while (ContinueReclaim)
{
lock (ClientSockets.SyncRoot)
{
for (int x = ClientSockets.Count - 1; x >= 0; x--)
{
Object Client = ClientSockets[x];
if (!((ClientHandler)Client).Alive)
{
ClientSockets.Remove(Client);
Console.WriteLine("A client left");
}
}
}
Thread.Sleep(200);
}
}
public static int Main(String[] args)
{
while (true)
{
StartListening();
}
return 0;
}
}
class ClientHandler
{
TcpClient ClientSocket;
bool ContinueProcess = false;
Thread ClientThread;
public ClientHandler(TcpClient ClientSocket)
{
this.ClientSocket = ClientSocket;
}
public void Start()
{
ContinueProcess = true;
ClientThread = new Thread(new ThreadStart(Process));
ClientThread.Start();
}
private void Process()
{
// Incoming data from the client.
string data = null;
// Data buffer for incoming data.
byte[] bytes;
if (ClientSocket != null)
{
NetworkStream networkStream = ClientSocket.GetStream();
ClientSocket.ReceiveTimeout = 100; // 1000 miliseconds
while (ContinueProcess)
{
bytes = new byte[ClientSocket.ReceiveBufferSize];
try
{
int BytesRead = networkStream.Read(bytes, 0, (int)ClientSocket.ReceiveBufferSize);
//BytesRead--;
if (BytesRead > 0)
{
Console.WriteLine("Bytes Read - Debugger " + BytesRead);
data = Encoding.ASCII.GetString(bytes, 0, BytesRead);
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] sendBytes = Encoding.ASCII.GetBytes("I rec ya abbas");
networkStream.Write(sendBytes, 0, sendBytes.Length);
if (data == "quit") break;
}
}
catch (IOException) { } // Timeout
catch (SocketException)
{
Console.WriteLine("Conection is broken!");
break;
}
Thread.Sleep(200);
} // while ( ContinueProcess )
networkStream.Close();
ClientSocket.Close();
}
} // Process()
public void Stop()
{
ContinueProcess = false;
if (ClientThread != null && ClientThread.IsAlive)
ClientThread.Join();
}
public bool Alive
{
get
{
return (ClientThread != null && ClientThread.IsAlive);
}
}
} // class ClientHandler
Heres my Client Code:
package com.example.socketclient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class SocketCode extends Activity {
public TextView txt;
protected SocketCore Conn;
public Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_code);
b = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
Conn = new SocketCore(this,txt);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Conn.execute();
}
});
}
}
SocketCore
package com.example.socketclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
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.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
class SocketCore extends AsyncTask<Context, Integer, String>
{
String text = "";
String finalText = "";
private Context ctx;
ProgressDialog dialog;
TextView Msg;
Socket socket;
public SocketCore(Context applicationContext,TextView Change)
{
// TODO Auto-generated constructor stub
ctx = applicationContext;
dialog = new ProgressDialog(applicationContext);
Msg = Change;
}
#Override
protected String doInBackground(Context... arg0) {
// TODO Auto-generated method stub
try {
InetAddress serverAddr = InetAddress.getByName("192.168.0.150");
Log.d("TCP", "C: Connecting....");
socket = new Socket(serverAddr,4444);
// Log.d("TCP", "C: I dunno ...");
String message = "Hello Server .. This is the android client talking to you .. First we are testing Server Crashing";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//serverReturnString = System.Text.Encoding.ASCII.GetString(response, 0, bytes);
out.println("quit");
//out.print("h");
while ((text = in.readLine()) != null) {
finalText += text;
if(text=="quit")
{
socket.close();
}
Log.d("TCP", "C: Done."+finalText);
}
// Msg.setText("LOLZ");
Log.d("TCP", "C: Sent.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} /*finally {
socket.close();
Log.d("TCP", "S: Closed");
} */
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
//dialog.setMessage("Recieved: "+finalText);
return "COMPLETE";
}
protected void onPostExecute(String x)
{
super.onPostExecute("Finished");
dialog.dismiss();
Msg.setText(finalText);
}
protected void onPreExecute()
{dialog.setTitle("Initializing Connection");
dialog.setMessage("Connecting");
dialog.show();
}
}
Server can read from android phone also the android client get message from server.
The Problem is whenever The Server detects connection and start Receives text and Sends Reply . The code doesnt accept more connection after that .
Note:
I tried to to test using C# client it works fine so i got a problem on the client side
You can't use more then AsyncTask.
The simplest approach is to move the code inside doInBackground() to a Runnable and then start a new Thread with that runnable on every click.
Example:
private Runnable rSocketCore = new Runnable() {
public void run() {
//here goes your connection code
}
};
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread(rSocketCore).start();
}
Note: You will also need an Handler if you want to communicate from the thread to the UI.
Regards.

Categories

Resources