PC和Android设备之间的客户端 - 服务器连接问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PC和Android设备之间的客户端 - 服务器连接问题相关的知识,希望对你有一定的参考价值。

我正在尝试将我的android设备连接到服务器,该服务器停留在我的PC上

这里试图创建一个套接字,但这个示例总是抛出异常

public void ref(View view) throws Exception
    {
        Socket s=new Socket("178.67.235.32",9876);
        try
        {
            BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
            PrintWriter out=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
            out.print("123");
            String str=in.readLine();
        }
        catch (Exception e)
        {
            Log.e("GG",e.toString());
        }
    finally
    {
        s.close();
    }

这是我正在运行的服务器

public class Server

{
 public static final ArrayList<InetAddress> users = new ArrayList<InetAddress>();
    static final int PORT = 9876;

    public static void main(String[] args) throws IOException
    {
        int i = 0;
        ServerSocket s = new ServerSocket(PORT);
        System.out.println("ServerStart");
        try
        {
            while (true)
            {
                Socket socket = s.accept();
                users.add(socket.getInetAddress());
                try
                {
                    System.out.println("yea");
                    new OneUserThread(socket, i);
                    i++;
                } catch (Exception e)
                {
                    System.out.println(e);
                }
            }
        } catch (Exception e)
        {
            System.out.println(e);
        } finally
        {
            s.close();
        }
    }
}

结果,我期待显示有关连接的消息,但我在logcat中有例外

我的logcat:32行-it正在创建Socket

12-03 14:37:58.574 5574-5574/ru.scapegoats.checkers E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: ru.scapegoats.checkers, PID: 5574
                                                                      java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                          at android.view.View.performClick(View.java:4463)
                                                                          at android.view.View$PerformClick.run(View.java:18770)
                                                                          at android.os.Handler.handleCallback(Handler.java:808)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:103)
                                                                          at android.os.Looper.loop(Looper.java:193)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5333)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:515)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
                                                                          at dalvik.system.NativeStart.main(Native Method)
                                                                       Caused by: java.lang.reflect.InvocationTargetException
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:515)
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                          at android.view.View.performClick(View.java:4463) 
                                                                          at android.view.View$PerformClick.run(View.java:18770) 
                                                                          at android.os.Handler.handleCallback(Handler.java:808) 
                                                                          at android.os.Handler.dispatchMessage(Handler.java:103) 
                                                                          at android.os.Looper.loop(Looper.java:193) 
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5333) 
                                                                          at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                          at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829) 
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645) 
                                                                          at dalvik.system.NativeStart.main(Native Method) 
                                                                       Caused by: android.os.NetworkOnMainThreadException
                                                                          at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156)
                                                                          at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
                                                                          at libcore.io.IoBridge.connectErrno(IoBridge.java:159)
                                                                          at libcore.io.IoBridge.connect(IoBridge.java:112)
                                                                          at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
                                                                          at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
                                                                          at java.net.Socket.startupSocket(Socket.java:579)
                                                                          at java.net.Socket.tryAllAddresses(Socket.java:131)
                                                                          at java.net.Socket.<init>(Socket.java:181)
                                                                          at java.net.Socket.<init>(Socket.java:153)
                                                                          at ru.scapegoats.checkers.InternetMenu.ref(InternetMenu.java:32)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                          at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                                                                          at android.view.View.performClick(View.java:4463) 
                                                                          at android.view.View$PerformClick.run(View.java:18770) 
                                                                          at android.os.Handler.handleCallback(Handler.java:808) 
                                                                          at android.os.Handler.dispatchMessage(Handler.java:103) 
                                                                          at android.os.Looper.loop(Looper.java:193) 
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5333) 
                                                                          at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                          at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829) 
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645) 
                                                                          at dalvik.system.NativeStart.main(Native Method) 
12-03 14:38:00.252 950-1170/? E/InputDispatcher: channel '42c4e900 ru.scapegoats.checkers/ru.scapegoats.checkers.InternetMenu (server)' ~ Channel is unrecoverably broken and will be disposed!
答案

您可以在日志中看到您的例外是NetworkOnMainThreadException。这意味着您正在尝试在主线程中打开套接字。您需要将客户更改为:

public void ref(View view) throws Exception {
    HandlerThread handlerThread = new HandlerThread("threadName");
    handlerThread.start();
    Handler mainHandler = new Handler(handlerThread.getLooper());

    Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
            Socket s = new Socket("178.67.235.32", 9876);
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
                out.print("123");
                String str = in.readLine();
            } catch (Exception e) {
                Log.e("GG", e.toString());
            } finally {
                s.close();
            }
        }
    };
    mainHandler.post(myRunnable);
}

此外,请确保您在清单中拥有权限:

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

以上是关于PC和Android设备之间的客户端 - 服务器连接问题的主要内容,如果未能解决你的问题,请参考以下文章

如何在windows pc和android设备之间建立蓝牙连接

无法在java中的2台PC套接字之间将客户端连接到服务器

我无法从其他设备连接到Flask服务器(=不是从localhost)

python客户端无法连接到java服务器

从 USB 连接的 Android 移动设备访问 PC 的本地主机

为android设置PC蓝牙服务器[重复]