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

时间:2017-12-03 11:57:12

标签: android sockets server client

我正在尝试将我的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!

1 个答案:

答案 0 :(得分:0)

您可以在日志中看到您的例外是/ DISPLAY PRODUCTS for USER / PUBLIC dinamically using a loop and then INSERT into HTML function showProduct() { lblProductList.innerHTML = ""; for ( var i = 0; i < ajProductDataFromServer.length; i++ ) { var lblProduct = '<div class ="lblProduct">' + '<a href="#' + ajProductDataFromServer[i].image + '">' + '<img src="' + ajProductDataFromServer[i].image + '" width="85%" class="lblProductImage" alt="product">' + '</a>' + '<a href="#_" class="lightbox" id="' + ajProductDataFromServer[i].image + '">' + '<img src="' + ajProductDataFromServer[i].image + '">' + '</a>' + '<h3 class ="lblProductName">' + ajProductDataFromServer[i].name + '</h3>' + '<h3 class ="lblProductPrice">' + 'Price:' + ' ' + ajProductDataFromServer[i].price + '<h3 class ="lblProductQuantity">' + 'Quantity:' + ' ' + ajProductDataFromServer[i].quantity + '</h3>' + '<button class="btnBuyProduct" data-productId="' + ajProductDataFromServer[i].id + '" >' + 'BUY PRODUCT' + '</button>' + '</div>'; lblProductList.insertAdjacentHTML( 'beforeend', lblProduct ); } } 。 这意味着您正在尝试在主线程中打开套接字。 您需要将客户更改为:

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);
}