Android TCP socket not working - java

I'm trying to connect to a server running on my desktop with an Android app.
I tried making a desktop Java program to test the connection and it worked with this code:
Socket socket = new Socket(HOST, PORT);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
It instantly prints the server welcome message, and I can see a new connection on the server.
However, the same code running on Android (on a separate thread) can't make the connection and I end up with a socket timeout exception.
private class NetworkThread implements Runnable {
Socket socket;
#Override
public void run() {
try {
socket = new Socket(HOST, PORT);
BufferedReader in
= new BufferedReader(
new InputStreamReader(socket.getInputStream()));
textStatus.setText(in.readLine());
}catch (IOException ex){
Log.i("Network", ex.toString());
ex.printStackTrace();
}
}
}
The thread is created here
public void onConnectBtnClick(View view) {
new Thread(new NetworkThread()).start();
}
HOST is the IP of the server and PORT is the port and have the same values in the Java and Android clients.
I have opened the port in my firewall but the android app still can't make the connection, and I get
java.net.ConnectException: failed to connect to GPC/192.168.1.5 (port 399): connect failed: ETIMEDOUT (Connection timed out)
The manifest has the INTERNET and ACCESS_NETWORK_STATE permissions. What am I doing wrong?

Related

Oreo: LocalOnlyHotspot is created, but socket exception happens

I am creating some testing app, and I need to connect several devices via Wi-Fi direct. On Android 8 the only way to do it is to create LocalOnlyHotspot. I have done it successfully, devices are connecting. However I need to transfer some strings between devices. For those reason I have made in separate threads
-> on server side
try{
int port = 9802;
ServerSocket serverSocket = new ServerSocket(port);
running = true;
while (running){
Socket socket = serverSocket.accept();
}
} catch (IOException e) { e.printStackTrace(); }
-> on client side
Socket socket = null;
try{
socket = new Socket(address, port);
} catch (IOException e) { e.printStackTrace(); }
I am always getting an exception on client's side
failed to connect to /192.168.43.1 (port 9802) from /:: (port 33044): connect failed: ECONNABORTED (Software caused connection abort)
As I have googled the reason is that the network has no internet connection.
How can I solve this problem? Is any other way to pass strings between 2 devices on Android 8 using Wi-Fi direct?
Thanks in advance.

SocketException when there is no internet connection

I'm programming an application which opens socket in service and sends some data to server and also listens for incoming data. Problem of course appears when connection with internet is lost on android device.
Here is code snippet where i get
java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed
out)
try{
mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);
BufferedReader in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
String s;
while((s = in.readLine())!= null){ //here error of course
...
}
mSocket.close();
}catch(Exception e){
e.printStackTrace();
}
Error is thrown when internet connection is lost and BufferedReader try to
readLine(). How to avoid this and why is it of course?
UPDATE
Error didn't bother me until I tryed to do next scenario:
1) run socket with wifi turned on
2) turn on also mobile data
3) turned off wifi
When wifi is turned off error occourse, but i'm connected to internet through mobile data, so I would like continu to listen on socket without error. Is this possible and how?
What you should do is reconnect a new socket in your catch block. The original connection is now gone, and I don't know a way of "seamlessly" swapping it.
try {
mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
...
} catch(Exception e){
try {
mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
...
} catch (Exception e2) {
// OK you really lost connectivity at this point, tell the user.
}
}

Android,Java,socket, determine remote host disconnect

I'm trying to code a TCP client in android java. Most works fine. But i have one issue. If the socket is connected and the remeote host shuts down or the network goes down or something else, the socket.getinputstream keeps blocking.
I don't know if the socket is still connected. I code in objective-c too and in objective-c i get an event that the socket forcefully shuts down and i can try to reconnect. So on objective c the socket tracks the state.
In java the socket and the inputstream is still connected or blocked even the socket is down. How can i check if the socket is still connected?
#Override
protected Void doInBackground(String... params) {
try {
String host = params[0];
int port = Integer.parseInt(params[1]);
SocketAddress sockaddr = new InetSocketAddress(host, port);
Socket socket = new Socket();
socket.connect(sockaddr,5000);
socket.setSoTimeout(7000);
out = new PrintWriter(socket.getOutputStream(), true);
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (mRun) {
try {
-----> mServerMessage = mBufferIn.readLine();
}catch (Exception e){
Log.d("my","hier3" + e.getMessage());
}
if (mServerMessage.trim() != null) {
sender.messageReceived(s2);
}else{
}
}
}
} catch (UnknownHostException e
) {
The question of how to detect if the remote peer/socket has closed the connection has been answered here as well as here.
Basically, the answers suggest that you attempt to read from the socket, and then observe what happens (read() returns -1, or readLine() returns null or your read methods raise EOFException.

Connection between Android Server and Laptop Client using same wifi

I want to connect android server application with laptop client java which connected on same wifi network.
i try the following code.
laptop client code
String IPToConnect="192.168.0.";
int i=0;
Socket skt;
PrintWriter pw;
try
{
for(i=105;i<=199;i++)
{
try
{
System.out.println(i);
skt=new Socket(IPToConnect+i,4444);
pw=new PrintWriter(skt.getOutputStream(),true);
pw.write("KP");
pw.flush();
pw.close();
skt.close();
}
catch(Exception ex)
{
continue;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
and android server code
private static ServerSocket serverSocket;
private static Socket client;
private static InputStreamReader inputStreamReader;
private static BufferedReader br;
private static String message;
serverSocket = new ServerSocket(4444)
try
{
client = serverSocket.accept();
inputStreamReader = new InputStreamReader(client.getInputStream());
br = new BufferedReader(inputStreamReader);
message = br.readLine();
System.out.println(""+message);
inputStreamReader.close();
client.close();
}
catch(Exception ex)
{
System.out.println("HELLO ERROR");
}
above code working fine for me
i want the program working like this
Android mobile app and laptop connected through same wifi network
when android app start it display the laptop on list when laptop start that client application
above code working fine but it may be not work when different router use different ip addresses means not start with(192.168.0) and it send request to all device means it time consuming
so please help me to solve the problem, in short i want to list laptop on android app when laptop start it client app
thank you

Simple Client Server communication

I am learning currently about client server communication using Java through sockets.
First of all I retrieve my own machine's IP Address using following code.
InetAddress ownIP=InetAddress.getLocalHost();
//the result being 192.168.56.1
Now I write the simple client server application using the above mentioned address as follow
public class SimpleClientServer {
public static void main(String[] args)
{
//sending "Hello World" to the server
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
clientSocket = new Socket("192.168.56.1", 16000);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
out.println("Hello World");
out.close();
in.close();
clientSocket.close();
}
catch(IOException e)
{
System.err.println("Error occured " + e);
}
}
}
The result hower reads a follow.
Error occured java.net.ConnectException: Connection refused: connect
What is the reason for this. Is it just the wrong host address?
From the code you have given you seem to suggest that there is currently nothing listening on port 16000 for the socket to connect to.
If this is the case you need to implement something like
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(16000);
}
catch (IOException e) {
System.err.println("Could not listen on port: 16000.");
System.exit(1);
}
More information can be found in the Java online documentation and a full example is included.
With sockets, no matter what language you're using, you either initiate a connection with socket_connect or you listen and accept with socket_listen and socket_accept. Your socket_connect call is trying to connect to an ip address that doesn't seem to be listening to anything.

Categories