Socket connection causes an exception on Android

Asked

Viewed 1,286 times

3

The code below works perfectly when only used with a Jbutton, but when passing to Android happens the exception (Exception).

I have located that the error is in

clientSocket = new Socket(serverIP, serverPort);

but I can’t understand why the mistake.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button button;

private static final String serverIP="192.168.1.177";
private static final int serverPort=80;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

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

    button.setOnClickListener(new ButtonListener());    

}

public class ButtonListener implements OnClickListener{

    @Override
    public void onClick(View v) {


        // Message that will be sent to Arduino
        String msgToServer;

        // Received message will be stored here
        String msgFromServer;

        try{

            // Making the socket connection
            Socket clientSocket = new Socket(serverIP, serverPort);

            // Debug
            System.out.println("Connected to:"+serverIP+" on port:"+serverPort);


            // OutputStream to Arduino-Server
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

            //BufferedReader from Arduino-Server
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            // Message tha will be sent
            msgToServer = "Turn ON LED 13";

            // Sending the message
            outToServer.writeBytes(msgToServer + '\n');

            // Debug
            System.out.println("sending to Arduino-Server: "+msgToServer);

            // Recieving the answer
            msgFromServer = inFromServer.readLine();

            // Print the answer
            System.out.println("recieved from Arduino-Server: " + msgFromServer);

            // Close the socket. Don't do this if you want to keep the connection
            clientSocket.close();

        }

        catch(Exception e){

        }

    }

}   

}       
  • The code seems correct. It would be interesting to have more information about which Exception is happening. But at first glance, I couldn’t find where you define serverIP and serverPort. Do both have values before the call Socket clientSocket = new Socket(serverIP, serverPort);? In addition, it would be right to create a Thread or a Task to make this communication, and not to do from within the click of the button, as it can lock the program and Android can indicate an ANR...

  • 1

    According to the Socket class documentation, "public Socket(String dstName, int dstport) throws Unknownhostexception, Ioexception" should be Unknownhostexception or Ioexception, but when I try to compare (Boolean Exception = e.equals(Unknownhostexception.class) or Boolean Exception = e.equals(Ioexception.class);) always return false. ServerIP and serverPort are set just below the line

  • 2

    So to know if an object is of a specific class you should use intanceof, for example: if (e instanceof UnknownHostException). However, the correct way to treat exceptions is to use the structure try-catch, creating a catch for each desired exception class. Now, about this error, I recommend switching the constructor line to Socket clientSocket = new Socket(InetAddress.getByName(serverIP), serverPort), but, you’re really initiating the variables serverIP and serverPort?

  • 3

    Is this code running on a real device or emulator? I say this because the emulator is on a network isolated from the local network, has only communication with the host machine. And the address to access the host machine is 10.0.2.2.

  • 2

    Added internet permission to the manifesto?

1 answer

1

Well, like Lucas said, Check that your Androidmanifest.xml has the following permissions:

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

Hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.