android socket client pc server using asynctask - android

I'm using asynctask to make connection between client (runnning on my android device) and server(running on my pc). When i launch the app i have to click on button to connect them, and my server pc program should show me in console device if client is connected but doesn't appear; my android client doesn't connect to my pc server.
Android client:
public class MainActivity extends ActionBarActivity {
Button send;
EditText txt;
TextView testo;
String response = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button) findViewById(R.id.send);
//txt = (EditText) findViewById(R.id.editText);
testo = (TextView) findViewById(R.id.textView1);
}
class AddStringTask extends AsyncTask<Void, String, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... unused) {
try {
Socket socketClient = new Socket("10.10.0.151",4321); //ipaddress of my pc server
} catch (UnknownHostException e) {
e.printStackTrace();
response = e.toString();
} catch (IOException e) {
e.printStackTrace();
response = e.toString();
}
testo.setText(response);
return (null);
}
#SuppressWarnings("unchecked")
#Override
protected void onProgressUpdate(String... item) {
}
#Override
protected void onPostExecute(Void unused) {
testo.setText(response);
}
}
public void buttonClick(View v){
new AddStringTask().execute();
}
}
Pc server:
public class Server {
public static Socket connection;
public static void main(String[] args) throws IOException {
System.out.println("Starting server on port number: 4321...");
ServerSocket server = new ServerSocket(4321);
while(true){
System.out.println("Waiting for clients...");
connection = server.accept();
System.out.println("Connected to: "+connection.getInetAddress().getHostAddress());
connection.close();
}
}
}
In my AndroidManifest.xml i've just added
<uses-permission android:name="android.permission.INTERNET"/>
If i launch client from pc in my server console i see the device connected but on android doesn't work..why?
Thanks

It's most likely the ip in the android side is wrong. use a private ip eg: 192.168.1.x. theese types of ip require you be on the same network. i think what you're trying to do is access the server from outside of the network and that requires port fkrwarding.

Related

How to auto connect to server?

I make a android application connect to server by using "com.mysql.jdbc.Driver".
I make a class for creating a connection as a AsyncTask.
public class MySqlConnection extends AsyncTask<Integer, Integer, Connection>{
protected void onPreExecute() {
//
}
protected Connection doInBackground(Integer... integers) {
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://"+ip+"/"+db_name+"?user="+username+"&password="+password);
return con;
}
protected void onPostExecute(Connection connection) {
delegate.setConnection(connection);
}
}
This class is called in OnCreate().
protected void onCreate(Bundle savedInstanceState) {
MySqlConnection sqlConnection = new MySqlConnection(MainActivity.this,utils.getConnection(),ip, dbname, user, password, new ConnectionResult() {
#Override
public void setConnection(Connection con) {
//set to static connection.
}
}
sqlConnection.execute(1);
}
It can work if a device can connect to server as initial.
But if I try to turn off Wifi, it cannot to re-connect by itself.
Client must restart the application for make it call OnCreate() again.
How to make it re-connection to server all the time?

Android Mqtt Publisher app stops unexpectedly

New to MQTT protocol. My code is working fine on eclipse platform. Now, trying to write publisher mqtt client for android and subscriber is running on eclipse. App is getting closed after launch. Please help me in the following code.
public class MainActivity extends AppCompatActivity
{
String text="HELOOO";
TextView textReply;
private MqttClient client;
public static final String TOPIC = "data";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
client = new MqttClient("http://IP-address:1883", MqttClient.generateClientId());
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
try {
client.connect();
MqttMessage mssg=new MqttMessage();
mssg.setPayload(text.getBytes());
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
}
}
Changes made after #arjun suggestions
public class MainActivity extends AppCompatActivity {
String text="HELOOO";
TextView textReply;
private MqttClient client;
public static final String TOPIC = "iot_data";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Publisher myClientTask = new Publisher();
myClientTask.execute();
}
}
class Publisher extends AsyncTask<Void, Void, Void>{
String text="helloo";
#Override
protected Void doInBackground(Void... voids) {
try {
MqttClient client = new MqttClient("tcp://Ip:1883", MqttClient.generateClientId());
client.connect();
MqttMessage mssg=new MqttMessage();
mssg.setPayload(text.getBytes());
client.publish("iot_data",mssg);
client.disconnect();
}catch(Exception e)
{
}
return null;
}
}
Maybe it has to do with that you are not specifying an ip adress properly on the client which leads to an exception where you do a system.exit(1);

Simple SignalR Android Example Issue

I am basically trying to send a message from my android to my server and the server to send back a response to my android app. I followed THIS tutorial.
Just a simple exercise to introduce myself in to SignalR using Azure Web API and Android.
My Complete Server code in C#:
public class TestHub: Hub {
public void SendMessage(string name, string message) {
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
public void SendClientMessage(CustomType obj) {
Clients.All.broadcastMessage("From Server", "Server got the message bro");
}
public class CustomType {
public string Name;
public int Id;
}
}
Complete Android Java code:
public class MainActivity extends AppCompatActivity {
Handler handler;
TextView statustext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
statustext = (TextView) findViewById(R.id.status);
Platform.loadPlatformComponent(new AndroidPlatformComponent());
// Change to the IP address and matching port of your SignalR server.
String host = "https://My-Service-name.azure-mobile.net/";
HubConnection connection = new HubConnection(host);
HubProxy hub = connection.createHubProxy("TestHub");
SignalRFuture < Void > awaitConnection = connection.start();
try {
awaitConnection.get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
hub.subscribe(this);
try {
hub.invoke("SendMessage", "Client", "Hello Server!").get();
hub.invoke("SendClientMessage",
new CustomType() {
{
Name = "Android Homie";
Id = 42;
}
}).get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
//I have no idea what the following method is for. Just followed the tutorial.. (blindly)
public void UpdateStatus(String status) {
final String fStatus = status;
handler.post(new Runnable() {
#Override
public void run() {
statustext.setText(fStatus);
}
});
}
public class CustomType {
public String Name;
public int Id;
}
}
Problems with this:
1. I get an exception:
java.util.concurrent.ExecutionException:
microsoft.aspnet.signalr.client.transport.NegotiationException: There
was a problem in the negotiation with the server
2. I feel like I haven't properly called the server from the Java code.
Should the URL be:
https://My-Service-name.azure-mobile.net/
or
https://My-Service-name.azure-mobile.net/api/signalr
Can someone clarify these doubts and help me set it up?

Socket.isConnected() make my android app force close

I don't know what happen with my source code about Socket in Android, when I use method
.isConnected()
My app always force close. And here my source code
public class MyActivity extends Activity {
private String IP;
private int PORT;
private Socket socket;
private PrintWriter printWriter;
private TextView text;
private EditText fieldIp;
private EditText fieldPort;
private Button connect;
private FrameLayout frameIP;
private String message;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
frameIP = (FrameLayout)findViewById(R.id.frameIP);
connect = (Button)findViewById(R.id.connect);
fieldIp = (EditText)findViewById(R.id.ip);
fieldPort = (EditText)findViewById(R.id.port);
text = (TextView)findViewById(R.id.keterangan);
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IP = fieldIp.getText().toString();
PORT = Integer.parseInt(fieldPort.getText().toString());
SocketConnect socketConnect = new SocketConnect(IP,PORT);
socketConnect.execute();
}
});
}
private class SocketConnect extends AsyncTask<Void, Void, Boolean> {
String ip;
int port;
public SocketConnect(String a, int b){
this.ip = a;
this.port = b;
}
#Override
protected Boolean doInBackground(Void... params) {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip,port));
if(socket.isConnected())
{
text.setText("Connected!");
}
else
{
text.setText("Failed to connect!");
}
} catch (IOException e) {
Log.e("MyActivity",e.getMessage());
}
finally {
startActivity(new Intent(getApplicationContext(),ListViewText.class));
}
return null;
}
}
}
And I use this in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
I hope you can help me guys :(
Change the doInBackground method as follows...
#Override
protected Boolean doInBackground(Void... params) {
boolean success = true;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port));
} catch (Exception e) {
success = false;
Log.e("MyActivity", e.getMessage());
}
return success;
}
Then add an onPostExecute method...
#Override
protected void onPostExecute(boolean result) {
if(result) {
text.setText("Connected!");
startActivity(new Intent(MyActivity.this, ListViewText.class));
}
else {
text.setText("Failed to connect!");
}
}
First thing you are calling UI operation outside of UI thread (that is why AsyncTask was created, to handle background job only in doInBackground) So problem about displaying text un TextView is solved...
But more important thing:
Never open Socket in AsyncTask. On Android developer site you can find following:
If you need to keep threads running for long periods of time, it is
highly recommended you use the various APIs provided by the
java.util.concurrent package such as Executor, ThreadPoolExecutor and
FutureTask.)
And that is exactly what you want to do. So use Service, Thread or those mentioned above instead.

Remote pc desktop from android device development

I'm trying to develop an android app with remote access functions. I have been searching similar posts about how remote desktop is made and what is the most efficient method, but i haven't found too mutch information about this.
Now i'm trying to send screenshots and display each one on a ImageView. It works, but the ImageView doesn't get refreshed until the app has ended. I tried to use postInvalidate() and invalidate() on an AsyncTask, but it didn't work.
I'd also like to know if there is a better way (or even different ways) to develop a remote desktop app. I wanna do it by myself, so i don't want to use any app as TeamViewer or similar.
Thanks for the help. Here is my code:
Client
public class MainActivity extends Activity {
static Button boton;
static byte[] imagen;
static ImageView imagenVista;
static Bitmap bmp;
static Socket clientSocket;
static OutputStream os;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boton = (Button)findViewById(R.id.button1);
boton.setOnClickListener(evento);
imagenVista = (ImageView)findViewById(R.id.imageView1);
}
private OnClickListener evento = new OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onClick(View v) {
if (boton.getText().equals("Start")){
boton.setText("Stop");
try{
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
while(true){
Socket clientSocket= new Socket();
InetSocketAddress addr=new InetSocketAddress("10.209.0.93", 5555);
clientSocket.connect(addr);
OutputStream os=clientSocket.getOutputStream();
os.write("capture".getBytes());
ObjectInputStream entrada = new ObjectInputStream(clientSocket.getInputStream());
construyendo_img(entrada)
new TareaSegundoPlano().doInBackground(entrada);
entrada.close();
os.flush();
clientSocket.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
else{
boton.setText("Start");
}
}
};
public void construyendo_img(ObjectInputStream entrada)throws IOException, ClassNotFoundException{
byte[] bytes_img = (byte[]) entrada.readObject();
ByteArrayInputStream entrada_img = new ByteArrayInputStream(bytes_img);
bmp = BitmapFactory.decodeByteArray(bytes_img, 0, bytes_img.length);
imagenVista.setImageBitmap(bmp);
}
public class TareaSegundoPlano extends AsyncTask<Void, ObjectInputStream, Void>{
protected void onPreExecute(){}
protected Void doInBackground(ObjectInputStream... params) {
imagenVista.invalidate();
return null;
}
protected void onProgressUpdate(Void... values) {}
protected void onPostExecute(Void result){}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
}
}

Categories

Resources