VB.Net Server & Android Client (Socket) Send & Receive - java

I am new to Android programming I wrote a simple Server(VB.NET) / Client(Java/Android) program. Text from Android/Java is send successfully to VB.Net but Response from VB.Net is not received in Android/Java (buffer.readLine() returns null)
Am I missing something?
Here are my Codes
VB.NET (Server)
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim server As New TcpListener(9999)
Dim client As New TcpClient
Dim stream As NetworkStream
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Start_Click(sender As Object, e As EventArgs) Handles Start.Click
Me.Text = "Waiting...."
Dim str As String
server.Start()
client = server.AcceptTcpClient
stream = client.GetStream()
Dim r_byt(client.ReceiveBufferSize) As Byte
stream.Read(r_byt, 0, client.ReceiveBufferSize)
Str = Encoding.ASCII.GetString(r_byt)
Label1.Text = str
End Sub
Private Sub Responce_Click(sender As Object, e As EventArgs) Handles Responce.Click
Dim s_byt() As Byte = Encoding.ASCII.GetBytes("Got it" & vbCr)
stream.Write(s_byt, 0, s_byt.Length)
stream.Flush()
stream.Close()
client.Close()
server.Stop()
End Sub
Android/Java(Client)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
Button buttonSend, buttonReceive;
private static Socket socket = null;
PrintStream stream = null;
BufferedReader buffer = null;
String string = "a";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
socket = new Socket("192.168.0.104", 9999);
stream = new PrintStream(socket.getOutputStream());
stream.println("Hi Server...");
buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
string = buffer.readLine();
Log.d("ServerActivity", " - " + string);
buffer.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}

It looks like you have a couple of issues:
In the server side, you are trying to read something from the socket
into r_byt, and you are not writing anything to it on cliente side.
When you press the send button on server side, r_byt still null and
that's what you receive on cliente side.
On client side the call to socket read is blocking and after a few
seconds will result in a ANR error (Application not Responding) in
the cliente. You should move the socket read to a different thread
from the UI. The newer Android versions don't even let you read from
a socket in the UI thread.
Regards.

Related

TCP/IP Android Device Connectivity Issues

I have a tcp/ip application in which Client 'A' gets it's coordinates and sends them to the server running on my pc. I am using local ips etc. This was running fine, I came out this morning however and I had an issue with my tp-link router and the lan, so I re installed my router and all connections (wi-fi) are back up and running. However, now when I try to run my app it won't work with my device.
If I run it through the emulator (i just have a string for testing) it works, I know that this is because both the server and the emulator are both on the same machine. My ip is correct, it is that of the machine the server is running on...I'm trying to teach myself this technology and do a project for college and I keep coming up against massive headaches like this. I've posted my client and server code below, is there anyone that might have any ideas? All setting are the same on the router and i'm sure as this is just connecting over a lan I don't have to forward any ports?
CLIENT A
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class Child extends Activity implements LocationListener {
private Socket s;
private PrintWriter p;
public static double latitude;
public static double longitude;
String coordinates;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.child);
LocationManager mlocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocationListener = new MyLocationListener();
mlocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocationListener);
String hello = "hello"; //FOR TESTING PURPOSES
Transmit (hello);
Log.d("test", "test");
}
public class MyLocationListener implements LocationListener {
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
longitude = location.getLongitude();
coordinates = ("TESTING " + latitude + longitude);
//Transmit(coordinates);
}
}
private void Transmit(final String message) {
Thread trans = new Thread(new Runnable() {
public void run() {
Log.d("TRANSMIT", "CALLED");
// TODO Auto-generated method stub
try {
s = new Socket("192.168.3.103", 1111); // connect to
// server
Log.d("CONNECTED", "Connected");
DataOutputStream _OutPut = new DataOutputStream(
s.getOutputStream());
_OutPut.writeBytes(message + "\n");
_OutPut.flush();
_OutPut.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
trans.start();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
SERVER
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class TCPServer {
public static void main(String[] args) throws Exception {
Socket s;
ServerSocket ss = new ServerSocket(1111);
System.out.println("Server started. Listening to the port 2001");
System.out.println("Server: waiting for connection ..");
while (true) {
try {
s = ss.accept();
if (s != null) {
InputStream fromChild = s.getInputStream();
while (s.isConnected()) {
System.out.println("Child Connected");
Scanner r = new Scanner(fromChild);
String location;
location = r.nextLine();
System.out.println(location);
}
}
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
So please, if anyone can help or throw some light on the situation I would be extremely grateful as I can't develop any further until I sort this problem.
Regards,
Gary
It certainly sounds like a connectivity issue between the phone and the server.
Double-check your ip address on the server and the phone and make sure they are on the SAME SUBNET (192.168.3.X), if not then you need to set up a forwarding rule on the router.
You can also verify connectivity by running a basic html server on the server box and point the browser on the phone to the server. Apache tomcat right of the box is easy to start and has a dashboard app already configured to run on startup. You can also test this from another computer on the same network to rule out your code and the phone altogether.
Read this:
http://developer.android.com/tools/devices/emulator.html#emulatornetworking
an excerpt from there :
Network Address Description
10.0.2.1 Router/gateway address
10.0.2.2 Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
10.0.2.3 First DNS server
10.0.2.4 / 10.0.2.5 / 10.0.2.6 Optional second, third and fourth DNS server (if any)
10.0.2.15 The emulated device's own network/ethernet interface
127.0.0.1 The emulated device's own loopback interface
basically if you run your server locally you should try and hit 10.0.2.2 address
from the emulator ---
Cheers,

how to generate a identified filename from url?

Now I have to download a file whose url has known. I need to save it to SD card when download action finished. The problem is I should know whether the file is existed before downloading. So I plan to save the file with a identified filename which is generated from url. So when I get the url I can calculate his corresponding filename. Which algorithm should I use?
BTW, JAVA is what I'm using.
Maybe, I have not told my requirement clearly. Fetch the filename "abc.png" from url "www.yahoo.com/abc.png" is not what I need. Because "www.google.com/abc.png" results the same filename. I need to generate a unique filename from url.
full example working ...i tried myself some days ago..
im sure it will help..
package com.imagedownloader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class ImageDownloaderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap=DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
ImageView img =(ImageView)findViewById(R.id.imageView1);
img.setImageBitmap(bitmap);
}
private Bitmap DownloadImage(String URL) {
// TODO Auto-generated method stub
Bitmap bitmap=null;
InputStream in=null;
try {
in=OpenHttpConnection(URL);
bitmap=BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String stingurl) throws IOException {
// TODO Auto-generated method stub
InputStream in=null;
int response=-1;
URL url = new URL(stingurl);
URLConnection conn=url.openConnection();
if(!(conn instanceof HttpURLConnection))
throw new IOException("not and http exception");
try{
HttpURLConnection httpconn=(HttpURLConnection)conn;
httpconn.setAllowUserInteraction(false);
httpconn.setInstanceFollowRedirects(true);
httpconn.setRequestMethod("GET");
httpconn.connect();
response=httpconn.getResponseCode();
if(response==HttpURLConnection.HTTP_OK)
{
in=httpconn.getInputStream();
}
}
catch(Exception ex)
{throw new IOException("Error connecting"); }
return in;
}
}

Server/Client Android to PC communication issue

Im trying to write a program using sockets having an android phone as the client and my PC as the server i found and slightly modified code for both sides and my server code works but i can't get the client activity to and i don't know acutally how to get the to programs to talk i want to basically be able to have either side input text and have it sent and set visable to the other i know how much of a stickler you guys are for questions so... How do i get these to communicate?
Client code (The emulator crashes before i can even begin to see the problem)
package com.example.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.*;
import java.net.*;
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener((android.view.View.OnClickListener) connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 9999);
connected = true;
while (connected) {
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("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
the Server code
import java.io.*;
import java.net.*;
/**
* Simple server using Java Sockets.
* #author Jonathan Engelsma (http://www.cis.gvsu.edu/~engelsma)
*
*/
public class Server {
/**
* #param args
*/
public static void main(String[] args) {
try {
// First we create a server socket and bind it to port 9999.
ServerSocket myServerSocket = new ServerSocket(9999);
// wait for an incoming connection...
System.out.println("Server is waiting for an incoming connection on host="
+ InetAddress.getLocalHost().getCanonicalHostName()
+ " port=" + myServerSocket.getLocalPort());
Socket skt = myServerSocket.accept();
// ok, got a connection. Let's use java.io.* niceties to read and write from the connection.
BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintStream myOutput = new PrintStream(skt.getOutputStream());
// attempt to read input from the stream.
String buf = myInput.readLine();
// if we got input, print it out and write a message back to the remote client..
if (buf != null) {
System.out.println("Server read: [" + buf + "]");
myOutput.print("got it");
}
// close the connection.
skt.close();
System.out.println("Server is exiting");
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Whoops, something bad happened! I'm outta here.");
}
}
}
Are you using
<uses-permission android:name="android.permission.INTERNET" />
In the Android Manifest? That could cause your problem.
if you are using ICS or JB, then you are probably being restricted from opening network connections from within your main activity. you will get an opaque error message regarding network permissions.
i cant repost my answer to another quite similar StackOverflow question here (it is considered spamming by moderators), but you can CHECK IT OUT HERE.
i posted a functional send and receive socket connector client using asynctask there.

How to use eclipse debug in android

I am attempting to use java FileInputStream to write some strings to a text file that will be stored on the android internal storage. However my virtual device keeps throwing an exception and I am not sure what or where I should be looking as the DDMS log cat function does not give me any useful information. I am using a try/catch structure with a stack trace print as shown below. I am not very familiar with the debug function in relation to android and I am not sure where else I can look to find out what is going on. Code is below.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText textBox;
private static final int READ_BLOCK_SIZE = 100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textBox = (EditText)findViewById(R.id.textView1);
Button saveBtn = (Button)findViewById(R.id.button1);
Button loadBtn = (Button)findViewById(R.id.button2);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = textBox.getText().toString();
try{
FileOutputStream fOut =
openFileOutput("textfile.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//---write the string to the file---
osw.write(str);
osw.flush();
osw.close();
//---display file saved message---
Toast.makeText(getBaseContext(), "File saved successfully!!", Toast.LENGTH_SHORT).show();
//---clears the EditText---
textBox.setText("");
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
loadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
FileInputStream fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[]inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while((charRead = isr.read(inputBuffer))>0){
//---convert the char to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
//---set the EditText to the text that has been read---
textBox.setText(s);
Toast.makeText(getBaseContext(), "File loaded successfully!!", Toast.LENGTH_SHORT).show();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
}
}
did you set your permissions in your manifest for writing?
and is your device a droidx (which when you plug in the USB cable, unmounts the external storage, making it inaccessible).
Why not run the debugger and put in debug points and see how far it gets before it crashes?

SocketChannel is not ready

again i have got a problem with socket programming in Android. My Problem is Selector.select() returns zero that there are no SocketChannels ready for writing. And again the same code works in normal Java but does not work in Android. Here is my code:
package com.test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class WebSocketTest extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SocketChannel channel = null;
SocketAddress socketAdress = new InetSocketAddress("10.0.0.1", 8787);
try {
channel = SocketChannel.open();
} catch (IOException e) {
Log.e("ERROR", "channel open");
}
try {
channel.configureBlocking(false);
} catch (IOException e1) {
Log.e("ERROR", "channel blocking");
}
try {
channel.connect(socketAdress);
} catch (IOException e) {
Log.e("ERROR", "channel connect");
}
try {
while(!channel.finishConnect())
{
}
} catch (IOException e1) {
Log.e("ERROR", "channel finishConnect");
}
Selector selector = null;
try {
selector = Selector.open();
} catch (IOException e) {
Log.e("ERROR", "selector open");
}
try {
channel.register(selector, channel.validOps());
} catch (ClosedChannelException e) {
Log.e("ERROR", "channel register");
}
boolean i = true;
while(i)
{
int readyChannels = 0;
try {
readyChannels = selector.select();
} catch (IOException e) {
Log.e("ERROR", "selector select");
}
if(readyChannels > 0)
{
i = false;
}
}
}
}
In Java readyChannels = 1. In Android it is 0.
Can anyone help me?
Emulator sits behind a virtual router. You need to configure Network Redirections (port forwarding) to make a certain port on emulator visible to the outside network (including your computer).
There are several issues with this NIO code.
Instead of connecting and then spinning around finishConnect(), possibly forever, you should connect before going into non-blocking mode. At the moment you're just burning the CPU, flattening the battery, etc.
You should only register OP_WRITE when you have something to write. It is normally 'ready', so if you register the channel for it permanently your selection loop will just spin. The only time OP_WRITE isn't ready is when you have filled the socket send buffer.

Categories