App connects to the server but can not communicate - java

I apologize in advance for my bad english
The app is able to connect to the server java, but hangs at the time of the exchange of data.
This is the client android code:
#SuppressLint("NewApi")
public class Connection extends IntentService{
private String tag = "Ciclo eventi";
private String user;
private String pass;
public Connection()
{
super("Connection");
}
public void onCreate(){
super.onCreate();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public void onStart(Intent intent, int startId){
Log.d(tag, "GetData");
Bundle extras = intent.getExtras();
user = (String) extras.get("User");
pass = (String) extras.get("Password");
Log.d(tag, user);
Log.d(tag, pass);
onHandleIntent(intent);
}
public int onStartCommand(Intent intent, int flags, int startId){
onHandleIntent(intent);
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
Log.d(tag, "CONNECTION CLOSED");
}
#Override
protected void onHandleIntent(Intent intent) {
Socket s=null;
BufferedReader in=null;
PrintWriter writer=null;
try {
Log.d(tag, "Try to connect");
s = getConnection("192.168.1.103", 5433);
Log.d(tag, "Connection done");
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
writer = new PrintWriter(s.getOutputStream(), true);
writer.println(user);
writer.println(pass);
Log.d(tag, "I've send the credential");
String resp = null;
resp = in.readLine();
Log.d(tag, "Receive the results");
if(resp.equals("done")){
Log.d(tag, "ACCEPT");
/*Intent i=new Intent(this,SecondActivity.class);
startActivity(i);*/
onDestroy();
}
else{
Log.d(tag, "Refused");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Socket getConnection(String ip, int port) throws IOException {
try {
KeyStore trustStore = KeyStore.getInstance("BKS");
InputStream trustStoreStream = getApplicationContext().getResources().openRawResource(R.raw.server);
trustStore.load(trustStoreStream, "keypass".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
SSLSocketFactory factory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket(ip, port);
//socket.setEnabledCipherSuites(getCipherSuitesWhiteList(socket.getEnabledCipherSuites()));
return socket;
} catch (GeneralSecurityException e) {
Log.e(this.getClass().toString(), "Exception while creating context: ", e);
throw new IOException("Could not connect to SSL Server", e);
}
}
public static String[] getCipherSuitesWhiteList(String[] cipherSuites) {
List<String> whiteList = new ArrayList<>();
List<String> rejected = new ArrayList<>();
for (String suite : cipherSuites) {
String s = suite.toLowerCase();
if (s.contains("anon") || //reject no anonymous
s.contains("export") || //reject no export
s.contains("null") || //reject no encryption
s.contains("md5") || //reject MD5 (weaknesses)
s.contains("_des") || //reject DES (key size too small)
s.contains("krb5") || //reject Kerberos: unlikely to be used
s.contains("ssl") || //reject ssl (only tls)
s.contains("empty")) { //not sure what this one is
rejected.add(suite);
} else {
whiteList.add(suite);
}
}
return whiteList.toArray(new String[whiteList.size()]);
}}
I need a service because i need a syncronous thread
This is the java server code:
public class SocketThread implements Runnable{
private Socket s1;
private BufferedReader in;
private PrintWriter out;
private String user = "admin";
private String pass = "ciao";
SocketThread(Socket s){
this.s1=s;
}
public void run(){
boolean loginDone = false;
String user1 = null;
String password1 = null;
String lati = null;
String longi = null;
String via = null;
System.out.println("Connected");
try {
in = new BufferedReader(new InputStreamReader(s1.getInputStream()));
out = new PrintWriter(s1.getOutputStream(), true);
user1 = in.readLine();
password1 = in.readLine();
System.out.println("User : "+user1+" Password : "+ password1);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("error on buffer creation");
e.printStackTrace();
}
System.out.println("Access done, wait for check credential");
do{
if(user1.compareTo(user)==0 && password1.compareTo(pass)==0){
loginDone = true;
out.println("done");
}
else{
out.println("noaccess");
}
}while(loginDone == false);
System.out.println("Login done");
try {
System.out.println("Close done");
s1.close();
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread off");
}}
Both the server and client crashes with no message error when exchanging data (both input and output)
The network is ok, the privileges of the android app are .INTERNET, .ACCESS_WIFI_STATE, .ACCESS_NETWORK_STATE
The server works well with a Java Desktop Client.
Thank you very much!

try using Volley
https://developer.android.com/training/volley/index.html
you can also use custom requests with volley.
https://developer.android.com/training/volley/index.html

Related

Android Sockets not working in reality

I am trying to connect an Android device to a java server. It works perfectly when I use the emulator but when I port it onto my phone there is no connection.
The aim of the code is to send a value from client to server, perform a calculation on it and return it back to the client to be displayed.
This is my server code:
public class ServerTest {
public static final int PORT_NUMBER = 8000;
protected Socket socket;
private ServerTest(Socket socket) {
this.socket = socket;
System.out.println("New client connected from " + socket.getInetAddress().getHostAddress());
connect();
}
public void connect() {
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String request = br.readLine();
if (request.equals("end")) {
System.out.println("Message received: " + request + ". Ending connection.");
request = "End Connection";
out.write(request.getBytes());
in.close();
out.close();
socket.close();
System.exit(0);
} else {
System.out.println("Message received: " + request);
request = calculatePi(request);
System.out.println("Output: " + request);
out.write(request.getBytes());
}
} catch (IOException ex) {
System.out.println("Unable to get streams from client");
} finally {
try {
in.close();
out.close();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("Welcome. IP address is: " + getIP());
ServerSocket server = null;
try {
server = new ServerSocket(PORT_NUMBER);
while (true) {
new ServerTest(server.accept());
}
} catch (IOException ex) {
System.out.println("Unable to start server.");
} finally {
try {
if (server != null)
server.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static String getIP() {
String ip = "";
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
// *EDIT*
if (addr instanceof Inet6Address) continue;
ip = addr.getHostAddress();
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
return ip;
}
and this is my client side code on device:
public class MainActivity extends AppCompatActivity {
TextView piResultTextView;
EditText addressEditText, messageEditText;
Button connectButton;
Handler handler = new Handler();
Results results;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
results = new Results();
addressEditText = findViewById(R.id.AddressEditText);
messageEditText = findViewById(R.id.MessageEditText);
connectButton = findViewById(R.id.ConnectButton);
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connect();
}
});
piResultTextView = findViewById(R.id.PiResultTextView);
}
public void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
String hostAddress = addressEditText.getText().toString();
int port = 8000;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(hostAddress, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(), "Unknown host: " + hostAddress, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to get streams from server", Toast.LENGTH_SHORT).show();
}
String input = messageEditText.getText().toString();
try {
out.println(input);
results.pi = in.readLine();
handler.post(new Runnable() {
#Override
public void run() {
piResultTextView.setText(results.pi);
}
});
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to read input stream from server", Toast.LENGTH_SHORT).show();
}
try {
out.close();
in.close();
echoSocket.close();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error closing streams", Toast.LENGTH_SHORT).show();
}
}
});
thread.start();
}
}

How to make a consistent WIFI connection in android

In my new android app, I have made a direct tcp connection to a device with specific IP and port, all working fine. Issue here is when Wifi disconnect it does not reconnect or send data again.
Inside my code below, I have a class Client.java and MainActivity.java below.
How can I do this?
#####################################################
public class Client extends AsyncTask<String, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
Socket socket = null; Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse = textResponse;
}
#Override
protected Void doInBackground(String... params) {
String str = params[0];
try {
smtpSocket = new Socket(dstAddress, dstPort);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = smtpSocket.getInputStream();
//smtpSocket.
/* notice: inputStream.read() will block if no data return */
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
//textResponse.setText(response);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
if (smtpSocket != null && os != null ) {
try {
os.writeBytes(str);
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}
//os.close();
//is.close();
//smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IO-Exception: " + e);
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//textResponse.setText("dweewed");
super.onPostExecute(result);
//super.cancel(true);
}
public void sendToPort(String str) throws IOException {
if (smtpSocket != null && os != null ) {
try {
os.writeBytes(str);
// os.close();
// is.close();
// smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}
#############################################################
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button buttonConnect, buttonClear;
TextView response;
Client myClient;
String editTextAddress = "10.0.1.50";
Integer editTextPort = 48;
boolean keepalive = true;
ConnectivityManager connManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myClient = new Client(editTextAddress, editTextPort, response);
connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
buttonConnect = (Button) findViewById(R.id.btnconnect);
buttonClear = (Button) findViewById(R.id.clear);
response = (TextView) findViewById(R.id.feedback);
buttonConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
response.setText("");
String dat = "Open";
try {
//String dat = "sec rfdgdf";
dat = dat + "\r\n";
myClient.sendToPort(dat);
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
response.setText("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
});
}
#Override
public void onResume(){
super.onResume();
response.setText("Resum`enter code here`e connected!");
}
}
You can implement the reconnect logic in the callback of registerNetworkCallback in the ConnectivityManager
The code you provided doesn't use connManager

Android socket principle and exception

i'm begginer with java socket in android. i'm have some problem and need help for solving them.
I'm connect to server Socket with bottom code and every thing is fine. but when call disconnect method and try to connect again i faced with problem such socket is null or BufferedReader object always return null after disconnect and connect again. maybe my disconnect way is wrong. what is the best way for disconnect socket at some time like intrupt internet and connect again?
Here is my code for connecting and disconnecting socket.
public class HelperSocket {
public static Socket socket = null;
public static DataOutputStream writer = null;
public static BufferedReader reader = null;
public static DataInputStream inputStream = null;
public static final String SOCKET_ADDRESS = "aUrlForSocket";
public static final int SOCKET_PORT = 6000;
public static final int SOCKET_TIMEOUT = 30000;
public static Thread clientThread;
public static boolean isConnected = false;
public static boolean connect() {
Utils.Log("StartConnect");
if (!isConnected) {
clientThread = new Thread(new Runnable() {
#Override
public void run() {
try {
InetAddress address = InetAddress.getByName(HelperSocket.SOCKET_ADDRESS);
socket = new Socket(address.getHostAddress(), SOCKET_PORT);
isConnected = true;
socket.setSoTimeout(SOCKET_TIMEOUT);
writer = new DataOutputStream(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
inputStream = new DataInputStream(socket.getInputStream());
while (HelperSocket.isConnected) {
Utils.Log("onWhile" + reader.hashCode());
try {
if (reader.readLine() != null) {
Utils.Log(reader.readLine() + "");
} else {
Utils.Log("getNullFromServer");
//data get null here :)
disconnect();
}
} catch (IOException e) {
Utils.Log("ProblemOnReadData" + e.getMessage());
e.printStackTrace();
}
}
} catch (IOException e) {
Utils.Log("SocketProblemAt connect:" + e.getMessage());
e.printStackTrace();
}
}
});
clientThread.start();
}
return true;
}
public static boolean disconnect() {
isConnected = false;
if (!clientThread.isInterrupted())
clientThread.interrupt();
if (socket != null) {
Utils.Log("SocketAndAllObjectCleared");
try {
socket.shutdownInput();
socket.shutdownOutput();
socket = null;
} catch (IOException e) {
e.printStackTrace();
}
/* stream = null;
reader = null;*/
}
return false;
}
}
I create a reciever in network connectivity change, and need to disconnect socket when device not connect to internet and connect again when internet connection established.
The receiver:
public class BroadcastChangeNet extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Utils.isNetworkConnected()) {
HelperSocket.connect();
Utils.Log("NetWorkConnect");
} else {
HelperSocket.disconnect();
Utils.Log("NetWorkDisConnect");
}
}
}
Checking network situation:
public static boolean isNetworkConnected() {
ConnectivityManager conMgr =
(ConnectivityManager) ApplicationClass.context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i == null)
return false;
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
return true;
}
From my point of view you simply need to create saprate Jave class, below is my code that i tested successfully,
import android.content.Context;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* Created by Kintan Patel on 01-08-2016.
*/
public class SocketConnection {
private Socket socket = null;
private OutputStream outputStream;
private DataOutputStream dataOutputStream;
private SessionHelper helper;
public String EstablishConnection(String token) {
// token = your message that write on socket server
String response;
try {
//socket = new Socket("192.168.0.24", 2129); // Testing Server
socket = new Socket("Your IpAddress", PORT NO);
outputStream = socket.getOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeUTF(token);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
response = br.readLine();
} catch (UnknownHostException e) {
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
return null;
} catch (SocketException e) {
e.printStackTrace();
response = "Sorry Fail to connect";
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
response = "Sorry Fail to connect";
return null;
} catch (Exception e) {
e.printStackTrace();
response = "Server Break";
return null;
} finally {
if (socket != null) {
try {
socket.close();
outputStream.close();
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
}
Now from your main class simply create the object of SocketConnection class and use EstablishConnection() method,
eg :
SocketConnection connection = new SocketConnection();
String token = "message that you want to write on server";
String response = connecation.EstablishConnection(token);
if you want to use AsynkTask than below is AsynkTask code :
private class ActivationTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
SocketConnection connection = new SocketConnection();
String token = "getActivation|" + params[0] + "|";
return connection.EstablishConnection(token);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
if (s != null) {
Log.e("RESULT" , s);
}
}
}

Why i'm getting timeout when trying to connect from my android device to the web server on my pc?

The web server on the pc is in c#
In the form1 constructor:
var ws = new WebServer(
request => Task.Run(() => SendResponseAsync(request)),
"http://+:8098/");
ws.Run();
This two methods
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("Local IP Address Not Found!");
}
public void Send(string ipaddress)
{
UdpClient client = new UdpClient();
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 15000);
byte[] bytes = Encoding.ASCII.GetBytes(ipaddress);
client.Send(bytes, bytes.Length, ip);
client.Close();
}
Then in timer tick event interval set to 1000ms
int countsends = 0;
private void timer2_Tick(object sender, EventArgs e)
{
if (countsends == 10)
{
Send(localipadd);
countsends = 0;
}
countsends += 1;
}
And the WebServer class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
namespace Automatic_Record
{
class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, Task<string>> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, Task<string>> method)
{
try
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
// URI prefixes are required, for example
// "http://localhost:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// A responder method is required
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
_listener.Prefixes.Add(s);
_responderMethod = method;
_listener.Start();
}
catch(AccessViolationException err)
{
string error = err.StackTrace;
}
}
}
On the pc side the c# i'm not getting any errors or exceptions and using break point i can see the pc ip on the network on the router on the method Send on variable ipaddress it's value is 10.0.0.1 i also logged in to my router settings and i saw that the pc is on 10.0.0.1
Now the java side in the android-studio where i'm trying to get the pc ip and to connect to it:
At the top of mainactivity: ( I tried before port 8098 but it didn't work so i tried 15000 but also didn't work still getting timeout message )
private String[] ipaddresses = new String[]{
"http://10.0.0.1:15000/?cmd=nothing"
};
Then a button click method calling from onCreate
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
The addListenerOnButton
public void addListenerOnButton()
{
btnClick = (Button) findViewById(R.id.connecttoserverbutton);
btnClick.setOnClickListener(new OnClickListener()
{
byte[] response = null;
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.statusTextView);
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
for (int i = 0; i < ipaddresses.length; i++)
{
counter = i;
try
{
response = Get(ipaddresses[i]);
}
catch (Exception e)
{
String err = e.toString();
}
if (response!=null)
{
try
{
final String a = new String(response, "UTF-8");
text.post(new Runnable()
{
#Override
public void run()
{
text.setText(a + " Oמ " + ipaddresses[counter]);
}
});
iptouse = ipaddresses[i].substring(0,ipaddresses[i].lastIndexOf("=")+1);
connectedtoipsuccess = true;
Logger.getLogger("MainActivity(inside thread)").info(a);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
Logger.getLogger("MainActivity(inside thread)").info("encoding exception");
}
Logger.getLogger("MainActivity(inside thread)").info("test1");
break;
}
else
{
}
}
counter = 0;
if (response == null)
{
text.post(new Runnable()
{
#Override
public void run()
{
text.setText("Connection Failed");
}
});
}
}
});
t.start();
}
});
}
And last the Get method
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
My android device is also connected to the same network on the router with wifi i checked on the router settings and i see my device.
I used a break point on the android-studio side inside the Get method.
It's getting to the line:
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
Then i click continue and that's it here it's hanging and instead keep going to the next line byte[] buf=new byte[10*1024]; after about 30 seconds it's jumping to: e.printStackTrace();
android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
failed to connect to /10.0.0.1 (port 15000): connect failed: ETIMEDOUT (Connection timed out)
I can't see any exceptions in the logcat.

Connection refused: when connecting a java client to an Android server(Emulator)

I've tried out almost everything.
Forwarding from ADB Shell using adb forward TCP:12345 TCP:12345
Using 10.0.2.2 (without forwarding) to listen to my host machine
Setting the INTERNET permission in the manifest
Setting the thread policy to permit all functions
I'm running my client java program in 12345 port and I have a ServerSocket in the Android program that listens over the same port. But when I run my client (after running the server program on the emulator) and enter the String that I want to transfer, I get the exception saying 'Connection Refused'.
java.net.ConnectException: Connection refused: connect
Here's my server program:
public class MainActivity extends Activity {
TextView tv;
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
public static final int SERVERPORT = 12345;
protected static final int MSG_ID = 0x1337;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = new TextView(this);
tv.setText("Nothing from client yet");
setContentView(tv);
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
// TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText(mClientMsg);
setContentView(tv);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(
new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
My Java client program is as follows:
public class TCPSender {
public static void main(String args[]) {
try {
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the file name:");
#SuppressWarnings("deprecation")
String f = dis.readLine();
File f1 = new File(f);
FileReader fr = new FileReader(f1);
Socket s = new Socket("127.0.0.1", 12345);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(f);
int c = 0;
while ((c = fr.read()) != -1)
pw.println(c);
System.out.println("File content are sent....");
fr.close();
s.close();
} catch (Exception e) {
System.out.println("" + e);
}
}
}

Categories