Connecting android client to C server - android

I am having trouble connecting my android client to a C server that I wrote. I found another thread with a similar question but unfortunately it was closed saying that it was too narrow. I hope that somebody can answer it here since this is relevant to me as well and all sample codes that I could find online only had the android client connecting to an android server. My client code is the following:
package edu.upenn.seas.cis542;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Try_uiActivity extends Activity
{
//private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "MY IP ADDRESS";
private boolean connected = false;
private Handler handler = new Handler();
final int SERVERPORT = 8080;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker3);
//t1.setRange(1, 5);
setContentView(R.layout.main);
}
/*
* When the Submit button is clicked, this method
* gets called.
*/
public void onSubmitClick(View view) {
int item1, item2, item3;
NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker1);
item1 = t1.getCurrent();
NumberPicker t2 = (NumberPicker)findViewById(R.id.numberPicker2);
item2 = t2.getCurrent();
NumberPicker t3 = (NumberPicker)findViewById(R.id.numberPicker3);
item3 = t3.getCurrent();
String userInput = "" + item1 + item2 + item3;
//Log.out("Before connecting");
if (!connected) {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Toast toast=Toast.makeText(this, serverAddr.toString(), Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Socket socket = new Socket(serverAddr, SERVERPORT);
connected = true;
} catch (Exception e) {
Toast toast=Toast.makeText(this, "Error2", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
e.printStackTrace();
connected = false;
}
}
}
}
I omitted what I want to do after it is connecting because just creating the socket already gives me an error. My C server opens a connection on the same port that the android program is connecting to. When I tested the server with a java client file, it worked fine. Does anybody know a solution to this? I also added the permissions to the Android Manifest, but that didn't solve the issue. Thanks!

Related

Android Socket Client through IOException

package com.example.tristan.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
private Socket client;
int serverPort = 8888;
String serverIP = "192.168.1.6";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fctClient();
}
public void fctClient() {
try {
Toast toast = Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT);
InetAddress addr = InetAddress.getByName(serverIP);
SocketAddress socketAddress = new InetSocketAddress(addr,serverPort);
//SocketAddress socketAddress = new InetSocketAddress(serverIP, serverPort);
client = new Socket();
toast.show();
client.connect(socketAddress);
toast.show();
toast.show();`enter code here`
client.close();
} catch (UnknownHostException e) {
Toast toast = Toast.makeText(getApplicationContext(), "KO1", Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
} catch (IOException e) {
Toast toast = Toast.makeText(getApplicationContext(), "KO2", Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
}
}
}
Hello,
I am trying to connect a client on Android on a Python server using a socket. The Python server is working well but the Android code fails to connect the server passing through a IOException.
Is anyone able to tell me my mistake? The code fails on line "client.connect(socketAddress);". This let me think that the wrong command is used to generate socketAddress.
I found the following link which met the same problem but his solution doesn't work for me.
(Java/Android) Client-side Socket throwing IOException
Thanking you in advance,
TL
You have a NetworkOnMainThreadExeption clearly visible in the logcat. All internet code should be executed in a thread or AsyncTask.
If you modify your code then remove all Toasts as they cannot be called in a thread or the doInBackground of an AsyncTask.

Activity closes on button press

I'm having a bit of trouble with a simple app I'm making.
I'll include the code:
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import java.net.URL;
public class login extends AppCompatActivity {
EditText user;
EditText pass;
boolean result_back;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button log = (Button) findViewById(R.id.btLogIn2);
log.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
login(v);
}
});
}
public void login(View v)
{
HttpClient client = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpResponse response = null;
user = (EditText) findViewById(R.id.eTUser);
String usuario = user.toString();
pass = (EditText) findViewById(R.id.eTPass);
String passw = pass.toString();
String parametros = "?usuario=" + usuario + "&password=" + passw;
HttpGet httpGet = new HttpGet("http://gie.byethost.com/acces.php" + parametros);
Toast toast2 = Toast.makeText(getApplicationContext(), "Enviando datos", Toast.LENGTH_SHORT);
toast2.show();
try
{
response = client.execute(httpGet, localContext);
toast2 = Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT);
toast2.show();
}
catch (Exception e)
{
}
// response.toString();
if (response.toString().equalsIgnoreCase("1"))
{
Toast toast1 = Toast.makeText(getApplicationContext(), "Login correcto", Toast.LENGTH_SHORT);
toast1.show();
} else
if (response.toString().equalsIgnoreCase("0"))
{
Toast toast1 = Toast.makeText(getApplicationContext(), "Error de login", Toast.LENGTH_SHORT);
toast1.show();
}
}
}
There's only one button here and neither toast is showing, so I don't see where the app is crashing. Also, I'm a bit new in Android programming, so this may have an obvious solution.
Any comments will be appreciated!
You're doing a network transaction on the main thread. Never do that (or any blocking behavior) on the main thread. Your app might be crashing with an error in logcat related to "StrictMode".
Instead, you need to put all your blocking work on another thread. Android has very specific patterns about how to do that. It's not like you would expect in a normal java app.
You might want to consider doing a search for "android asynchronous programming" and learn about things like AsyncTask, Loader, and Service. There are a lot of great tutorials out there on how to use them. Please don't use Thread directly, as that will only cause you pain.

my app could not send a message from my real device to emulator! What is goes wrong? is needed to more settings?

i am new by android.I have started work with a simple chat app. I wrote a short code by UDP socket one for client and one for server.Now i have some issues at connectivity android real device which client app installed on it , and emulator device which server app run on it.
Client app is a simple code which must set IP for connection to emulator and also has a EditText for sending a message.(I at this point set 10.0.2.2 or 10.0.2.15. But my app could not send a message from my real device to emulator! What is goes wrong? is needed to more settings?)
Server app has only a textView for getting and showing recived message.
here is Client code:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ClienttextchatActivity extends Activity
{
private String udpMsg=null;
Handler hand=new Handler();
EditText edtSetIp=null , edtText=null;
Button btnSetIp=null , btnSend=null;
static String ip=null;
static final String LOG_TAG = "UdpStream";
static final int PORT = 8888;
static final int BUF_SIZE=4096;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edtText=(EditText)findViewById(R.id.edtText);
edtSetIp=(EditText)findViewById(R.id.edtSetIp);
btnSetIp=(Button)findViewById(R.id.btnSetIp);
btnSend=(Button)findViewById(R.id.btnSend);
btnSetIp.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
ip=edtSetIp.getText().toString();
}
});
btnSend.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Thread mythread=new Thread(new th1() );
mythread.start();
}
});
}
//#############################################
public class th1 implements Runnable
{
public void run()
{
udpMsg =edtText.getText().toString();
Log.d(LOG_TAG,udpMsg);
DatagramSocket ds = null;
try
{
ds = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName(ip);
Log.d(LOG_TAG,"address server address created.");
DatagramPacket dp;
dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, PORT);
ds.send(dp);
Log.d(LOG_TAG,"packet send.");
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ds != null)
{
ds.close();
}
}
}//end run
}//end class th
}
Make sure emulator is started, then in ADB shell, type this command, it will show ip address of emulator.
adb shell
ifconfig etho

how to send data (a string) to a paired device in android?

I am working on bluetooth for the first time. I got the list of paired devices. Now my requirement is I need to send some data (a string) to the device. how can I do that? I tried searching but didn't find anything useful. Could anyone help out this?
Something like this might suffice:
DataOutputStream os;
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
BluetoothDevice remoteDevice;
remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getApplicationContext(), "Discovered: " + remoteDeviceName + " address " + remoteDevice.getAddress(), Toast.LENGTH_SHORT).show();
try{
BluetoothDevice device = bluetooth.getRemoteDevice(remoteDevice.getAddress());
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
BluetoothSocket clientSocket = (BluetoothSocket) m.invoke(device, 1);
clientSocket.connect();
os = new DataOutputStream(clientSocket.getOutputStream());
new clientSock().start();
} catch (Exception e) {
e.printStackTrace();
Log.e("BLUETOOTH", e.getMessage());
}
}
};
registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
bluetooth.enable();
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
public class clientSock extends Thread {
public void run () {
try {
os.writeBytes("anything you want"); // anything you want
os.flush();
} catch (Exception e1) {
e1.printStackTrace();
return;
}
}
}
You will also need a lot of imports such as these:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.UUID;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
note that not all imports are necessary for this example code, your IDE might help you to sort them out for you.
Pass data on the os.writeBytes("anything you want"); // anything you want line.
You will also need Permissions

Socket connection test, not working and receive data from hyperterminal

I am creating a socket connection in android eclipse for receiving data first i need to test the connection but the page is not opening on my app, i use a listactivity for my classes.
I want to receive data from my pc(hyperterminal), i have connected a hardware device to my computer which behaves like a router and i want to connect my android phone to the router via Wifi and receive data on my phone as i type on the hyperterminal.
package com.exa.bullseye;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.io.OutputStream;
public class WifiReceive extends Activity {
EditText ip;
EditText s_port;
Button connect;
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(R.layout.wifireceive);
ip = ((EditText)findViewById(R.id.ip));
s_port = ((EditText)findViewById(R.id.port));
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String address = ip.getText().toString();
InetAddress addr = InetAddress.getByName(address);
int port = Integer.parseInt(s_port.getText().toString());
// Creates a stream socket and connects it to the specified port
// number at the specified IP address. Blocks until the connection succeeds.
Socket socket = new Socket(addr, port);
Toast.makeText(getApplicationContext(), "Socket Connected",
Toast.LENGTH_LONG).show();
socket.close();
}
catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(), "Host not found",
Toast.LENGTH_LONG).show();
}
catch (IOException ioe) {
Toast.makeText(getApplicationContext(), "I/O Exception",
Toast.LENGTH_LONG).show();
}
}
});
}
}

Categories

Resources