Artish1
Artish1

Reputation: 143

Android socket connection to server on computer not connecting

I've recently wanted to send a request to a test server (being hosted on the same local wifi) and just explore the education in Android app developing.

What I've created so far was a small quick server on my laptop:

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;


public class Main {

public static void main(String[] args) throws Exception
{
    System.out.println("Starting...");
    ServerSocket server = new ServerSocket(1234);
    Socket socket = server.accept();
    loop(socket);



}


public static void loop(Socket socket) throws Exception
{

    Scanner socketScanner = new Scanner(socket.getInputStream());
    int num = socketScanner.nextInt();
    System.out.println("Received: " + num);
    num *= 2;

    PrintStream out = new PrintStream(socket.getOutputStream());
    out.println(num);

    loop(socket);
}


}

The test client (on the laptop as well) works great:

import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;


public class Main {
public static void main(String[] args) throws Exception
{
    Socket socket = new Socket("localhost",1234);

    loop(socket);


}


public static void loop(Socket socket) throws Exception
{
    Scanner scanner = new Scanner(System.in);
    Scanner socketScanner = new Scanner(socket.getInputStream());
    System.out.println("Input number:");
    int num = scanner.nextInt();
    PrintStream p = new PrintStream(socket.getOutputStream());
    p.println(num);

    int response = socketScanner.nextInt();
    System.out.println("Received: " + response);
    loop(socket);
}

}

But then I'd try to connect with the android emulator from Android Studio and after running a request a message shows that (unfortunately) the application has stopped.

Yes, I have added in the user perms to allow connection?

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.artish1.testapplication" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And finally the actual code being run:

 public static  TextView status;
public static EditText ip;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    status = (TextView)findViewById(R.id.statusText);
    ip = (EditText)findViewById(R.id.ipText);
    Log.i(TAG, "Application: onCreate!");

    Button button = (Button)findViewById(R.id.payBenButton);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try{
                status.setText("Sending...");
                Log.i(TAG,"Starting socket sending... to: localhost");
                Socket socket = new Socket("localhost",1234);
                Log.i(TAG, "Connected.");
                int num = Integer.parseInt( ((EditText) findViewById(R.id.numberText)).getText().toString());
                PrintStream out = new PrintStream(socket.getOutputStream());
                out.println(num);
                Log.i(TAG, "Sending: " + num);

                BufferedReader reader = new BufferedReader(new      InputStreamReader(socket.getInputStream()));

                String response = reader.readLine();
                status.setText("Received: " + response);
                Log.i(TAG, "Received: " + response);


            }catch(SocketException e)
            {
                Log.i(TAG,e.getMessage());
            }catch(IOException e)
            {
                Log.i(TAG,e.getMessage());
            }

        }
    });


}

I've spent a good 3-4 hours fiddling around but I just don't understand what the problem is?

Upvotes: 0

Views: 2860

Answers (2)

HandyPawan
HandyPawan

Reputation: 1106

  1. Use full URL instead of "localhost"
  2. android:usesCleartextTraffic="true" //Add in your menifest

Upvotes: 0

BNK
BNK

Reputation: 24114

Try replace "localhost" by your laptop IP or the 10.0.2.2 IP. Hope this help!

Upvotes: 1

Related Questions