I am a complete noob at Android, only at the level of basic (1 or 2 line) Activities activated by buttons, but I would like to create a really simple app that, when I tap the app icon, it fires and forgets a message to a listening server on my Windows 8 PC. The phone is connected as a simple media device, without Kies, via a USB cable.
I can get as far as a message box lying and saying the message was sent. I need to know what kind of comms channel to use, e.g. a COM port or what, and how to send data over that from Android. On the Windows side, once I've established how to communicate, I can help myself.
starting with the desktop side of this application:
You can use the ADB (Android debug bridge) to establish a tcp/ip socket connection via port between the device and desktop. The command is :
adb forward tcp:<port-number> tcp:<port-number>
to run this command in your java program, you will have to create a process builder wherein this command ets executed on a child shell.
For windows you may need to use:
process=Runtime.getRuntime().exec("D:\\Android\\adt-bundle-windows-x86_64-20130729\\sdk\\platform-tools\\adb.exe forward tcp:38300 tcp:38300");
sc = new Scanner(process.getErrorStream());
if (sc.hasNext())
{
while (sc.hasNext())
System.out.print(sc.next()+" ");
System.out.println("\nCannot start the Android debug bridge");
}
sc.close();
}
The function required to execute adb commands :
String[] commands = new String[]{"/bin/sh","-c", command};
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String s = null;
while ((s = stdInput.readLine()) != null)
{
sb.append(s);
sb.append("\n");
}
while ((s = stdError.readLine()) != null)
{
sb.append(s);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
Above method will take the above command as a string and execute it on a child shell
//Extracting Device Id through ADB
device_list=CommandExecutor.execute("adb devices").split("\\r?\\n");
System.out.println(device_list);
if(device_list.length>1)
{
if(device_list[1].matches(".*\\d.*"))
{
device_id=device_list[1].split("\\s+");
device_name=""+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.manufacturer")+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.model");
device_name=device_name.replaceAll("\\s+"," ");
System.out.println("\n"+device_name+" : "+device_id[0]);
device=device_id[0];
System.out.println("\n"+device);
}
else
{
System.out.println("Please attach a device");
}
}
else
{
System.out.println("Please attach a device");
}
CommandExecutor is a class which has the execute method in it. The code of the execute method is the same as posted above.
This will check if any device is connected and if it connected, it will return it unique id number.
It is preferable to use id number while executing adb commands like :
adb -s "+device_id[0]+" shell getprop ro.product.manufacturer
OR
adb -s <put-id-here> shell getprop ro.product.manufacturer
Note that '-s' is necesarry after adb.
Then using adb forward commnd you need to establish a tcp/ip socket. Here the desktop will be the client and mobile/device will be the server.
//Create socket connection
try{
socket = new Socket("localhost", 38300);
System.out.println("Socket Created");
out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hey Server!\n");
new Thread(readFromServer).start();
Thread closeSocketOnShutdown = new Thread() {
public void run() {
try {
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
Runtime.getRuntime().addShutdownHook(closeSocketOnShutdown);
}
catch (UnknownHostException e) {
System.out.println("Socket connection problem (Unknown host)"+e.getStackTrace());
} catch (IOException e) {
System.out.println("Could not initialize I/O on socket "+e.getStackTrace());
}
Then you need read from the server i.e. the device :
private Runnable readFromServer = new Runnable() {
#Override
public void run() {
try {
System.out.println("Reading From Server");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((buffer=in.readLine())!=null) {
System.out.println(buffer);
}catch (IOException e) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
The 'buffer' will contain what device will send from its end of the app.
Now in your mobile application,you will need to open the same connection and siple write data to it out buffer
public class TcpConnection implements Runnable {
public static final int TIMEOUT=10;
private String connectionStatus=null;
private Handler mHandler;
private ServerSocket server=null;
private Context context;
private Socket client=null;
private String line="";
BufferedReader socketIn;
PrintWriter socketOut;
public TcpConnection(Context c) {
// TODO Auto-generated constructor stub
context=c;
mHandler=new Handler();
}
#Override
public void run() {
// TODO Auto-generated method stub
// initialize server socket
try {
server = new ServerSocket(38300);
server.setSoTimeout(TIMEOUT*1000);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//attempt to accept a connection
try{
client = server.accept();
socketOut = new PrintWriter(client.getOutputStream(), true);
socketOut.println("Hey Client!\n");
socketOut.flush();
syncContacts();
Thread readThread = new Thread(readFromClient);
readThread.setPriority(Thread.MAX_PRIORITY);
readThread.start();
Log.e(TAG, "Sent");
}
catch (SocketTimeoutException e) {
// print out TIMEOUT
connectionStatus="Connection has timed out! Please try again";
mHandler.post(showConnectionStatus);
try {
server.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
catch (IOException e) {
Log.e(TAG, ""+e);
}
if (client!=null) {
try{
// print out success
connectionStatus="Connection succesful!";
Log.e(TAG, connectionStatus);
mHandler.post(showConnectionStatus);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
private Runnable readFromClient = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Log.e(TAG, "Reading from server");
socketIn=new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = socketIn.readLine()) != null) {
Log.d("ServerActivity", line);
//Do something with line
}
socketIn.close();
closeAll();
Log.e(TAG, "OUT OF WHILE");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void closeAll() {
// TODO Auto-generated method stub
try {
Log.e(TAG, "Closing All");
socketOut.close();
client.close();
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Runnable showConnectionStatus = new Runnable() {
public void run() {
try
{
Toast.makeText(context, connectionStatus, Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
}
}
Using Managed.adb in c#
AndroidDebugBridge bridge = AndroidDebugBridge.
CreateBridge(#"C:\Users\bla\AppData\Local\Android\Sdk\platform-tools\adb.exe", true);
List<Device> devices = AdbHelper.Instance.
GetDevices(AndroidDebugBridge.SocketAddress);
devices[0].CreateForward(38300, 38300);
Then create a server socket on android to that port.
server = new ServerSocket(38300);
server.setSoTimeout(TIMEOUT * 1000);
socket = server.accept();
and client socket on C#
TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect("127.0.0.1", 38300);
Related
For network analysis and testing purposes, I'm trying to setup a way of DoSing the wifi hotspot AP of my own phone.
I've researched it thoroughly, but I'm going in circles. So far I've focused on various kinds of ping and packet flooding. But nothing seems to degrade traffic flow of connhected devices. Here are some things I've tried:
ping approach:
public class PacketFlood extends Thread {
public void run() {
Runtime runtime = Runtime.getRuntime();
Process proc;
try {
proc = runtime.exec("ping -i 0.2 -l 3 -c 1 " + "192.168.43.1"); // <--- ip of the hotspot AP
proc.waitFor();
int exit = proc.exitValue();
proc.destroy();
proc = null;
}
catch (IOException e){
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
PacketFlood tpint = new PacketFlood(); ////// , ppppsub[1]);
/////// 5-6-15-am tworig:
tpint.start();
}//////run
socket approach:
class ClientThread implements Runnable {
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket("192.168.43.1", 5555); // <-- ip of AP on arbitrary port
if (socket.isConnected()) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(....a very long string here.....);
socket.close();
} else {
Log.e("nnnnnnnooooooo", "Socket is NOT connected");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Thread(new ClientThread()).start();
}//////run
i've created an android application in which, android application act as the client, and server resides in the desktop application.
suppose there are 10 android application runs the same at a time on 10 different android tablets, when one updation received from one tablet, the desktop application sends the updation to all other remaining tablets. how could the server knows how many clients are connected and how to send the message to all the clients
what i plan is to run a server in all android so that when one updation received from one tablet, the desktop application sends the updation to all other remaining tablets.
can anyone please tell me some suggestion regarding this.
Client side
private int SERVER_PORT = 9999;
class Client implements Runnable {
private Socket client;
private PrintWriter out;
private Scanner in;
#Override
public void run() {
try {
client = new Socket("localhost", SERVER_PORT);
Log.d("Client", "Connected to server at port " + SERVER_PORT);
out = new PrintWriter(client.getOutputStream());
in = new Scanner(client.getInputStream());
String line;
while ((line = in.nextLine()) != null) {
Log.d("Client", "Server says: " + line);
if (line.equals("Hello client")) {
out.println("Reply");
out.flush();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Server class
class ServerThread implements Runnable {
private ServerSocket server;
#Override
public void run() {
try {
server = new ServerSocket(SERVER_PORT);
Log.d("Server", "Start the server at port " + SERVER_PORT
+ " and waiting for clients...");
while (true) {
Socket socket = server.accept();
Log.d("Server",
"Accept socket connection: "
+ socket.getLocalAddress());
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
private Socket clientSocket;
private PrintWriter out;
private Scanner in;
public ClientHandler(Socket clietSocket) {
this.clientSocket = clietSocket;
}
#Override
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream());
in = new Scanner(clientSocket.getInputStream());
String line;
Log.d("ClientHandlerThread", "Start communication with : "
+ clientSocket.getLocalAddress());
out.println("Hello client");
out.flush();
while ((line = in.nextLine()) != null) {
Log.d("ClientHandlerThread", "Client says: " + line);
if (line.equals("Reply")){
out.print("Server replies");
out.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You could save the Sockets in a List and send a message through all the OutputStreams in that List:
Socket socket = Server.accept();
sockets.add(socket); //sockets is an ArrayList<Socket>
public void sendMessageToEveryone(String msg) {
for(Socket s : sockets) {
s.getOutputStream().write(msg.getBytes());
s.getOutputStream().flush();
}
You could use the Google Cloud Messaging service.
Take a look at this page:
https://developer.android.com/google/gcm/index.html
I am developing an application to send a request to port 502 and want to read the response from the same port.
This is what i tried so far
public class Autoamtion extends Activity {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.v("on create", "on create");
final ToggleButton fanOn = (ToggleButton) findViewById(R.id.toggleButton1);
fanOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (fanOn.isChecked()) {
Toast.makeText(Autoamtion.this, "Fan is On",
Toast.LENGTH_SHORT).show();
Log.v("on create", "on create");
try {
echoSocket = new Socket("192.168.1.19", 502);
out = new PrintWriter(echoSocket.getOutputStream(),
true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to:192.168.1.19");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stdIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
echoSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
Toast.makeText(Autoamtion.this, "Fan is Off",
Toast.LENGTH_SHORT).show();
}
});
}
}
i just installed one simulator which opens the port 502. i confirmed that port which gets open after running this simulator.
i just established the connection with 502 port. i am not getting any response from there.
Please guide me through this so i can make this working. Any advice and help would be appreciated .
Thanks
You should post stackTrace as well, to check what's failling.
At least one thing is not consistent in your information, your refer in the text port 503 and in your code you are using echoSocket = new Socket("192.168.1.19", 502); connecting to port 502.
I have a BufferedReader, when I try to read it, it just hangs and doesn't do anything, am I doing this right? I am using this in an AsyncTask.
Edit: I have a tablet connected to the Wi-Fi, this connects to my computer which is broadcasting on 172.20.104.203 on port 5334, I can see when the thread starts, but nothing after that.
Here my code:
try {
final BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
final String msg;
msg = (line);
Log.d("DeviceActivity", msg);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ClientAcivtity: Exception",
String.valueOf(e));
}
EDIT
I have all the right permissions or anything, I was doing this outside a AsyncTask and it worked perfectly, moved it because I didn't want it in the main thread.
-Edit , here is the full code.
public class NetworkTask extends AsyncTask<Void, byte[], Boolean> {
Socket nsocket; // Network Socket
InputStream nis; // Network Input Stream
OutputStream nos; // Network Output Stream
private Handler handler = new Handler();
Boolean connected = false;
public static final int PORT = 5334;
public String SERVERIP = "172.20.104.203";
Socket socket;
#Override
protected void onPreExecute() {
Log.i("AsyncTask", "onPreExecute");
InetAddress serverAddr;
try {
serverAddr = InetAddress.getByName(SERVERIP);
socket = new Socket(serverAddr, PORT);
connected = true;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ClientAcivtity: Exception", String.valueOf(e));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ClientAcivtity: Exception", String.valueOf(e));
}
}
#Override
protected Boolean doInBackground(Void... params) { // This runs on a
// different thread
boolean result = false;
try {
Log.d("ClientActivity", "C: Connecting...");
if (socket != null) {
int cont = 1;
while (cont == 1) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// where you issue the commands
out.println("getPos");
Log.d("ClientActivity", "C: Sent " + "getPos");
} catch (Exception e) {
Log.e("ClientAcivtity: Exception",
String.valueOf(e));
}
try {
final BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
final String msg;
msg = (line);
Log.d("DeviceActivity", msg);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ClientAcivtity: Exception",
String.valueOf(e));
}
cont--;
}
Log.d("ClientActivity", "C: Closed.");
}
} catch (Exception e) {
Log.e("ClientAcivtity: Exception", String.valueOf(e));
}
return result;
}
#Override
protected void onProgressUpdate(byte[]... values) {
if (values.length > 0) {
Log.i("AsyncTask", "onProgressUpdate: " + values[0].length
+ " bytes received.");
}
}
#Override
protected void onCancelled() {
Log.i("AsyncTask", "Cancelled.");
}
#Override
protected void onPostExecute(Boolean result) {
if (socket != null) {
if (connected) {
if (result) {
Log.i("AsyncTask",
"onPostExecute: Completed with an Error.");
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.i("AsyncTask", "onPostExecute: Completed.");
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
My guess is that when you write out the command "getPos" the underlying BufferedWriter is not actually sending the data out on the line (you should verify this with tcpdump/wireshark). If this is the case, the server doesn't responsed to the readLine(), since it never got a command. To verify this claim, add out.flush(); after out.println("getPos");
Really, tcpdump will probably give you a better answer then anyone on the forums.
Also see http://developer.android.com/reference/java/io/BufferedWriter.html
Try doing it like this:
final BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
StringBuffer buf = new StringBuffer();
int i;
while((i = in.read()) != -1){
buf.append((char) i);
}
String data = buf.toString();
Reading from sockets is a quite difficult issue depending where the socket is actually connected to and how the other side responds.
If the other side is extremely fast than it can provide the socket with enough data so that the read routines actually work fine. However if there is a delay in the other side of any kind (just needs to be slower than your read routine incl the small default timeout) then your read fails even though there might be data on the other side - just arriving a little too slow at the socket.
Depending on your needs you may wrap your own minimum and maximum timer around the read routine.
Please provide more information and we can better understand the issue.
In many cases it is necessary to have a minimum timeout large enough for the other side to push data to the socket - but you might also need a maximum time for how long you actually want to wait for data to arrive.
UPDATE:
first the runnable to start the monitoring thread. You may use monitoringCanRun in your loop to interrupt the thread if required. And monitoringThreadIsAlive can be used to know if the thread is still running.
monitoringCanRun = true;
new Thread(new Runnable() {
public void run() {
monitoringThreadIsAlive = true;
performMonitoring();
monitoringThreadIsAlive = false;
}
}).start();
}
and performMonitoring looks like:
public void performMonitoring() {
while (monitoringCanRun) {
... do your read in the while loop
...you might like to insert some delay before trying again...
try { //we delay every partial read so we are not too fast for the other side
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I use the following code to receive the data from a particular port. It's not working in Android. But sending data to particular port is working fine.
public class UDPDemo extends Activity {
private TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.recv_message);
try {
DatagramSocket clientsocket=new DatagramSocket(9876);
byte[] receivedata = new byte[1024];
while(true)
{
DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
Log.d("UDP", "S: Receiving...");
clientsocket.receive(recv_packet);
String rec_str = new String(recv_packet.getData());
tv.setText(rec_str);
Log.d(" Received String ",rec_str);
InetAddress ipaddress = recv_packet.getAddress();
int port = recv_packet.getPort();
Log.d("IPAddress : ",ipaddress.toString());
Log.d(" Port : ",Integer.toString(port));
}
} catch (Exception e) {
Log.e("UDP", "S: Error", e);
}
}
}
If you are using the emulator you may need setup redirects, remember the emulator is behind a virtual router.
In other words, type these commands in;
telnet localhost 5554
redir add udp:9876:9876
and try again.
Used Port numbers
Create Datagram packet
try {
mDataGramSocket = new DatagramSocket(Config.PORT_NUMBER);
mDataGramSocket.setReuseAddress(true);
mDataGramSocket.setSoTimeout(1000);
} catch (SocketException e) {
e.printStackTrace();
}
Call below function through AsyncTask
Create Function to receive infinitely
public void receive() {
String text;
byte[] message = new byte[1500];
DatagramPacket p = new DatagramPacket(message, message.length);
try {
while (true) { // && counter < 100 TODO
// send to server omitted
try {
mDataGramSocket.receive(p);
text = new String(message, 0, p.getLength());
// If you're not using an infinite loop:
//mDataGramSocket.close();
} catch (SocketTimeoutException | NullPointerException e) {
// no response received after 1 second. continue sending
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
// return "error:" + e.getMessage();
mReceiveTask.publish("error:" + e.getMessage());
}
// return "out";
}