简体   繁体   English

TCP 套接字安卓客户端

[英]TCP Socket Android Client

I have a problem with a android socket client.我有一个 android 套接字客户端的问题。 I try to send a string from an android client to a python server.我尝试将字符串从 android 客户端发送到 python 服务器。 I create a test app in netbeans and the code its working, but on android doesn't work.我在 netbeans 中创建了一个测试应用程序,其代码可以正常工作,但在 android 上不起作用。 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 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.你的问题是你把这段代码放在哪里,因为Android禁止在主UI中放置任何网络操作,因为它会阻止与用户的界面,导致用户体验非常差,用户可能会卸载你的应用程序。

You have to place that code within a Thread or an AsyncTask .您必须将该代码放在ThreadAsyncTask 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.我怀疑是您 Logcat 的StrictMode$AndroidBlockGuardPolicy.onNetwork AndroidBlockGuardPolicy.onNetwork。 Try to add:尝试添加:

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

inside onCreate() and before addListenerOnButton() .onCreate()内部和addListenerOnButton()之前。 It is also a good idea to double check AndroidManifest.xml for granted permissions.仔细检查 AndroidManifest.xml 以获得授予的权限也是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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