user1705850
user1705850

Reputation: 111

Android newbie - socket client without thread

I'd like to finalize a very simple app: send a TCP packet to a server. Server answer, for the moment does not matter.

So, I write a very simple class where I create a socket, send the message and then, close the socket.

The app crash in s.send(msg.serialized); and I do not understand why.

Code in myActivity:

        final TcpSender s = new TcpSender();

        switch (tab_ID) {
            case 1:
                rootView = inflater.inflate(R.layout.fragment_tab1, container, false);

                //----- btn_BotolaUp
                final ToggleButton btn_light = (ToggleButton) rootView.findViewById(R.id.btn_light);
                btn_light.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        String toastmessage;

                        if (isChecked) {
                            msg.serialize("Identifier", "ON", "datafield1", "datafield2");
                            toastmessage = "Light ON";
                        } else {
                            msg.serialize("Identifier", "OFF", "datafield1", "datafield2");
                            toastmessage = "Light OFF";
                        }

                        s.send(msg.serialized);
                        Toast.makeText(rootView.getContext(), toastmessage, Toast.LENGTH_SHORT).show();
                    }
                });

            case.... 
                etc

TcpSender Class is defined as follow:

import android.util.Log;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpSender {
Socket socket;

public boolean send(String messagetosend) {

    try {
        InetAddress serverAddr = InetAddress.getByName("192.168.1.1");
        socket = new Socket(serverAddr, 10000);
        Log.d("Net", "Socket created");

        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
        Log.d("Net", "PrintWriter out");

        out.print(messagetosend);
        Log.d("Net", "Message: " + messagetosend + " ->sent");
        socket.close();
        Log.d("Net", "Socket closed");

    } catch (UnknownHostException err) {
        err.printStackTrace();
        Log.e("Net", "UnknownHostException err");
        return (false);
    } catch (IOException err) {
        err.printStackTrace();
        Log.e("Net","IOException err");
        return (false);
    }

    Log.d("Net","send successful!");
    return (true);
}

}

Could someone help me to understand what I'm doing wrong ?

Upvotes: 0

Views: 347

Answers (2)

Lawrence Chen
Lawrence Chen

Reputation: 21

Google prevents you from using main thread for the network tasks, and here is the reason:

Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread.

and make sure the proper permissions are included in manifest.

you may figure out this issue and learn more with the official docs.

Upvotes: 1

JJF
JJF

Reputation: 2777

The short answer to your question is that you are going to need a separate thread if you want to do network operations. Android does not allow network operations on your app's main thread.

Upvotes: 2

Related Questions