I have java code that sends strings via ip to a python script. The code works perfectly with the emulator but when I successfully install the app via usb to my phone it does not work. Here is the code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn_python = findViewById(R.id.python);
final Button btn_movie = findViewById(R.id.movie);
final Button btn_hw = findViewById(R.id.homework);
btn_python.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
send py = new send();
message = "python";
Log.i("Button", "Button works");
System.out.println("whatever");
py.execute();
}
});
btn_movie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
send mov = new send();
message = "movie";
mov.execute();
}
});
btn_hw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
send hw = new send();
message = "homework";
hw.execute();
}
});
}
class send extends AsyncTask<Void,Void,Void>{
Socket s;
PrintWriter pw;
#Override
protected Void doInBackground(Void...params) {
System.out.println("whatevernumbertwo");
try {
System.out.println("whatevernumberthree");
s = new Socket("ip address", 7800);
Log.i("Socket", "connects to socket");
pw = new PrintWriter(s.getOutputStream());
Log.i("output stream", "Output stream works");
pw.write(message);
Log.i("write", "Write works");
pw.flush();
Log.i("flush", "Flush works");
pw.close();
s.close();
} catch (UnknownHostException e) {
System.out.println("Fail");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Fail");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
As I mentioned this works on the emulator but not on the actual device. The proper permissions have also been given. What am I doing wrong? Thanks in advance.
After much digging around, it turned out to be the server's firewall all along. That explains why (apparently) no exception was thrown, and why the code didn't seem to execute; it was executing, it was just getting stuck inside Socket() (during the connect).
Surely Socket() is, in fact, throwing an IOException; it probably just takes a while.
The code works on the emulator because, as it is operating on the same machine, it is behind the firewall.
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.
I searched for some websites and learned that the way to communicate between android device(phone) and PC via USB is to have an app implementing serversocket on the phone and another app implementing client socket on PC. I kinda fixed the phone side's app(no exception now), but I got an exception "Ljava.lang.StackTraceElement" trying to initiate a socket("localhost", 38300). Does anybody know what's going on with this and how I can fix it? I attached both side's of the code below.
My step to get it to run is as follows
: environment:
Samsung Android phone, Linux PC, Android Studio developer run on Linux
: connection step
open android studio
install one app on phone
install another app on pc android emulator
launch phone side app and click on button to attempt to wait for connection
at this step, adb devices will have two devices
adb -s emulator-5554 -s 1234567890(my phone) forward tcp:38300 tcp:38300
launch pc side android emulator app and click on the button to initiate client socket
NOTE: as you all can see that I can use android studio "Android Monitor" window to see both phone's and PC's app shell's log.
phone side
package com.example.seanhsu.androiddevice_serversocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Scanner;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidDevice_ServerSocket extends AppCompatActivity implements OnClickListener{
public static final String TAG = "Connection";
public static final int TIMEOUT = 10;
Intent i = null;
TextView tv = null;
private String connectionStatus = null;
private String socketData = null;
private Handler mHandler = null;
ServerSocket server = null;
String msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_device__server_socket);
// Set up click listeners for the buttons
View connectButton = findViewById(R.id.connect_button);
connectButton.setOnClickListener(this);
View onBtn = findViewById(R.id.hdmi_on);
onBtn.setOnClickListener(this);
View offBtn = findViewById(R.id.hdmi_off);
offBtn.setOnClickListener(this);
// i = new Intent(this, Connected.class);
mHandler = new Handler();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.connect_button:
tv = (TextView) findViewById(R.id.connection_text);
// initialize server socket in a new separate thread
new Thread(initializeConnection).start();
msg = "Attempting to connect...";
Log.e(TAG, "1 "+msg);
Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
break;
case R.id.hdmi_on:
Log.e(TAG, "disconnect" + Globals.socketOut);
if (Globals.socketOut != null) {
Globals.socketOut.println("hdmiOn");
Globals.socketOut.flush();
msg = "disconnect hdmi on";
Log.e(TAG, "2 "+msg);
Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
}
else
{
msg = "disconnect hdmi on is null";
Log.e(TAG, "3 "+msg);
Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
}
break;
case R.id.hdmi_off:
Log.e(TAG, "disconnect" + Globals.socketOut);
if (Globals.socketOut != null) {
Globals.socketOut.println("hdmiOff!!");
Globals.socketOut.flush();
msg = "disconnect hdmi off";
Log.e(TAG, "4 "+msg);
Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
}
else
{
msg = "disconnect hdmi off is null";
Log.e(TAG, "5 "+msg);
Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
}
break;
}
}
private Runnable initializeConnection = new Thread() {
public void run() {
Socket client = null;
// initialize server socket
try {
server = new ServerSocket(38300);
server.setSoTimeout(TIMEOUT * 5000);
// attempt to accept a connection
client = server.accept();
Globals.socketIn = new Scanner(client.getInputStream());
Globals.socketOut = new PrintWriter(client.getOutputStream(),
true);
// Globals.socketIn.
} catch (SocketTimeoutException e) {
// print out TIMEOUT
Log.e(TAG, "aaa=== " + e);
msg = "Connection has timed out! Please try again";
Log.e(TAG, "6 "+msg);
//Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();//method error, this causes program terminated
mHandler.post(showConnectionStatus);
} catch (IOException e) {
Log.e(TAG, "bbb=== " + e);
msg = "IO Exception";
Log.e(TAG, "7 "+msg);
//Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();//method error, this causes program terminated
} finally {
// close the server socket
try {
if (server != null)
server.close();
} catch (IOException ec) {
Log.e(TAG, "ccc=== " + ec);
Log.e(TAG, "Cannot close server socket" + ec);
msg = "Cannot close server socket";
Log.e(TAG, "8 "+msg);
//Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();//method error, this causes program terminated
}
}
if (client != null) {
Globals.connected = true;
// print out success
connectionStatus = "Connection was succesful!";
Log.e(TAG, "9 "+connectionStatus);
mHandler.post(showConnectionStatus);
while (Globals.socketIn.hasNext()) {
socketData = Globals.socketIn.next();
mHandler.post(socketStatus);
}
// startActivity(i);
}
}
};
/**
* Pops up a "toast" to indicate the connection status
*/
private Runnable showConnectionStatus = new Runnable() {
public void run() {
Log.e(TAG, "10 "+connectionStatus);
Toast.makeText(getBaseContext(), connectionStatus,
Toast.LENGTH_SHORT).show();
}
};
private Runnable socketStatus = new Runnable() {
public void run() {
TextView tv = (TextView) findViewById(R.id.connection_text);
tv.setText(socketData);
}
};
public static class Globals {
public static boolean connected;
public static Scanner socketIn;
public static PrintWriter socketOut;
}
}
PC side
package com.example.seanhsu.pchost_clientsocket_withactivity;
import android.support.v7.app.AppCompatActivity;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Scanner;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class PCHost_ClientSocket_with_Activity extends AppCompatActivity implements OnClickListener{
Socket socket;
PrintWriter out;
Scanner sc;
String msg;
private String TAG = "PCHost_ClientSocket_withActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pchost__client_socket_with_);
View connectButton = findViewById(R.id.connect_button);
connectButton.setOnClickListener(this);
//when the emulator start running, it's already in the emulator shell, so it cann't execute adb command
//execAdb();
}
public void onClick(View v) {
//cannot run on main thread
//need to run on another thread, otherwise it will get android.os.NetworkOnMainThreadException exception
new Thread(initializeConnection).start();
//initializeConnection();
/*while(sc.hasNext()) {
System.out.println(System.currentTimeMillis() + " / " + sc.nextLine());
Log.e(TAG, "12 "+System.currentTimeMillis() + " / " + sc.nextLine());
}*/
}
//cannot run on main thread
//need to run on another thread, otherwise it will get android.os.NetworkOnMainThreadException exception
private Runnable initializeConnection = new Thread() {
public void run() {
msg = "initializeConnection";
Log.e(TAG, msg);
//Create socket connection
try{
Log.e(TAG, "============0============");
socket = new Socket("localhost", 38300);
Log.e(TAG, "============1============");
out = new PrintWriter(socket.getOutputStream(), true);
Log.e(TAG, "============2============");
//in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
sc=new Scanner(socket.getInputStream());
Log.e(TAG, "============3============");
// add a shutdown hook to close the socket if system crashes or exists unexpectedly
Thread closeSocketOnShutdown = new Thread() {
public void run() {
try {
Log.e(TAG, "============4============");
socket.close();
msg = "closeSocketOnShutdown socket close";
Log.e(TAG, msg);
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e(TAG, "============5============");
e.printStackTrace();
msg = "closeSocketOnShutdown IOException";
Log.e(TAG, msg);
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
}
}
};
Log.e(TAG, "============6============");
Runtime.getRuntime().addShutdownHook(closeSocketOnShutdown);
Log.e(TAG, "============7============");
} catch (UnknownHostException e) {
//Print.fatalError(“Socket connection problem (Unknown host)”+e.getStackTrace());
msg = "Socket connection problem (Unknown host)"+e.getStackTrace();
Log.e(TAG, msg);
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
//Print.fatalError(“Could not initialize I/O on socket “+e.getStackTrace());
msg = "Could not initialize I/O on socket "+e.getStackTrace();
Log.e(TAG, msg);
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
}
}
};
}
I keep getting exception:
Could not initialize I/O on socket [Ljava.lang.StackTraceElement;#14710f5
Originally I also has IO exception on phone side app, but I add <uses-permission android:name="android.permission.INTERNET"/> in the manifest, it's OK now. Therefore, I also add <uses-permission android:name="android.permission.INTERNET"/> in PC side app's manifest, but still can't fix this problem.
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
I'm trying to connect my 'Galaxy S' to my Panasonic PLC(or even other PC itself) but I always get an SocketTimeoutException. My android version is 2.3.3:
IP-PLC: 192.168.2.99
IP-GalaxyS: I don't know how to check it
Mask of the network: 255.255.255.0
The PLC is connected directly with the wi-fi router, and I connect my cell phone to this network.
package com.example.communication;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import android.util.Log;
public class TryConnection implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.2.99");
Socket socket = new Socket(serverAddr, 9094);
Log.e("SUCESS", "SUCESS");
} catch(SocketTimeoutException e) {
Log.e("SOCKET TIMEOUT", "SOCKET TIMEOUT", e);
} catch (IOException e) {
Log.e("CONNECTION ", " ERROR", e);
}
}
and my MainActivity Class:
package com.example.communication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendTag(View view) {
TryConnection tryconnection = new TryConnection();
Thread thread = new Thread(tryconnection);
thread.start();
}
}
Do you have any idea for why is it happening ?
It happened with me also, restarted eclipse to resolve the issue.