简体   繁体   中英

TCP Socket Android Client

I have a problem with a android socket client. I try to send a string from an android client to a python server. I create a test app in netbeans and the code its working, but on android doesn't work. I verify if data comes to server with print of string on server.

Here is my code:

package com.example.tcp_button;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

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




public class MainActivity extends Activity {

    Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);

        addListenerOnButton();

    }

    public void addListenerOnButton() {

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

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                DataOutputStream dataOutputStream = null;
                Socket socket = null;    

                try {
                    socket = new Socket("192.168.0.106", 5555);
                    dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    dataOutputStream.writeUTF("on"); 
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        });

    }

}

here is the log :

03-27 20:38:49.388: E/AndroidRuntime(2367): FATAL EXCEPTION: main
03-27 20:38:49.388: E/AndroidRuntime(2367): android.os.NetworkOnMainThreadException
03-27 20:38:49.388: E/AndroidRuntime(2367):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at libcore.io.IoBridge.connect(IoBridge.java:112)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at java.net.Socket.startupSocket(Socket.java:566)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at java.net.Socket.tryAllAddresses(Socket.java:127)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at java.net.Socket.<init>(Socket.java:177)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at java.net.Socket.<init>(Socket.java:149)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at com.example.tcp_button.MainActivity$1.onClick(MainActivity.java:46)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at android.view.View.performClick(View.java:4439)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at android.widget.Button.performClick(Button.java:142)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at android.view.View$PerformClick.run(View.java:18395)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at android.os.Handler.handleCallback(Handler.java:725)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at android.os.Looper.loop(Looper.java:176)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at android.app.ActivityThread.main(ActivityThread.java:5299)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at java.lang.reflect.Method.invokeNative(Native Method)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at java.lang.reflect.Method.invoke(Method.java:511)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
03-27 20:38:49.388: E/AndroidRuntime(2367):     at dalvik.system.NativeStart.main(Native Method)

You should try making the Socket this way:

Socket socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);

// Use this just in case you have to read from the server
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

// This will be used to send to the server
OutputStream out = socket.getOutputStream();
out.write("This is my message".getBytes("UTF-8"));

---- EDIT ----

After seeing your update, your code has nothing to do with it. Your problem is where have you put this piece of code, as Android forbids placing any network operation in the main UI because it would block the interface with the user, resulting in a very poor user experience and probably the user will uninstall your app.

You have to place that code within a Thread or an AsyncTask . If you're starting with it, you probably want to try with the latter. Here's a nice example .

Try flushing the outputstream:

dataOutputStream.writeUTF("on"); 
dataOutputStream.flush(); 

You also might want to close it when you're done.

My suspicion is StrictMode$AndroidBlockGuardPolicy.onNetwork of your Logcat. Try to add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

inside onCreate() and before addListenerOnButton() . It is also a good idea to double check AndroidManifest.xml for granted permissions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM