简体   繁体   English

Android Socket客户端未连接到服务器

[英]Android Socket client doesn't connect to the server

I'm trying to connect an android client to a pc server, but the client always crashes and doesn't connect to the server. 我正在尝试将android客户端连接到pc服务器,但是客户端总是崩溃并且没有连接到服务器。 the server is composed of two methods, one that wait for a client to connect and another that print the client connected (I didn't use thread, i only connect one client) Server (i will show only the first method): 服务器由两种方法组成,一种等待客户端连接,另一种打印连接的客户端(我不使用线程,我仅连接一个客户端)服务器(我将仅显示第一种方法):

public Socket listeningClient () 
{
    try 
    {
        server = new ServerSocket(8080);
        client = server.accept();
        server.close();
    }
    catch (Exception e)
    {
        System.out.println(e.getMessage());
        System.exit(1);
    }
    return client;
}

in the client there are a button that call the method to create the socket on click: 在客户端中,有一个按钮,该按钮在单击时调用该方法来创建套接字:

Client 客户

public class Client {
  String IP = "192.168.1.4";
  int portaServer = 8080;
  Socket miosocket = null;

  public void connetti() {
    try {
        InetAddress nomeServer = InetAddress.getByName(IP);
        miosocket = new Socket(nomeServer, portaServer);
        miosocket.close();
    }
    catch (UnknownHostException e) {
        e.printStackTrace();
        Log.e("MyApp", "UnknownHost");
    }
    catch (Exception e) {
        e.printStackTrace();
        Log.e("MyApp", "Exception");
        System.exit(1);
    }
  }
}

The app always crash at the line: miosocket = new Socket(nomeServer, portaServer); 该应用程序总是在行上崩溃: miosocket = new Socket(nomeServer, portaServer); and Throws the Exception(the second one). 并引发异常(第二个异常)。 Can someone please tell me if is my code that is wrong(I'm pretty sure that the problem is the code) or there are problem on the server? 有人可以告诉我我的代码是否错误(我很确定问题出在代码上)还是服务器上有问题?

(in the AndroidManifest.xml I used these permission : (在AndroidManifest.xml中,我使用了以下权限:

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

)

Per the exception you quoted in your comments, you cannot perform blocking IO on the main thread. 根据注释中引用的异常,您无法在主线程上执行阻塞IO。 You need to spawn a thread (or use AsyncTask and do the work there. 您需要产生一个线程(或使用AsyncTask并在那里进行工作。

If you are really trying to host a server on an Android service, you should do so by creating a Service and using that to host a thread that starts the server and processes requests. 如果您确实要在Android服务上托管服务器,则应通过创建Service并将其用于托管启动服务器并处理请求的线程来实现。

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

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