简体   繁体   English

AsyncTask和套接字在Android Java中不起作用

[英]AsyncTask and socket not working in android java

I'm making a simple app client-server in java, i want my phone to receive and send messages to my pc, i'm on same LAN and my pc's ip is 192.168.1.8, my serverSocket is running on port 7777. for some reason my client android cant connect i think it is because i created a socket in a thread, i have read that i should use AsyncTask or Handle, i tried with that too but i get an exception too. 我正在用Java创建一个简单的应用程序客户端-服务器,我希望我的手机能够接收和发送消息到我的PC,我在同一局域网中,我的PC的IP为192.168.1.8,我的serverSocket在端口7777上运行。由于某些原因,我的客户端android无法连接,我认为这是因为我在线程中创建了一个套接字,我已经读到我应该使用AsyncTask或Handle,我也尝试过这样做,但是我也遇到了异常。

Class server: 类服务器:

public class MyServer implements Runnable{


private ServerSocket server;
private ObjectInputStream in;
private ObjectOutputStream out;
private Socket clientedConnected;

public ExampleServerZNuC(){
    try {
        server= new ServerSocket(7777);
        System.out.println("server opened on port 7777");
    } catch (IOException ex) {
        Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
    }

}
public void sendMessage(String message){
    try {
        out.writeObject(message);
        out.flush();
    } catch (IOException ex) {
        Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}
public void sendNotifiy(){
  try {
        out.writeObject("Send Notify");
        out.flush();
    } catch (IOException ex) {
        Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
    }

}
public String getMessage(){
  return "";
}
public void run(){
    System.out.println("method run started");
    System.out.println("Waiting for a client to connect");
    try {
        Socket clientedConnected;
        clientedConnected = server.accept();
        System.out.println("A client connected : "+clientedConnected.getInetAddress().getHostAddress());
        in= new ObjectInputStream(clientedConnected.getInputStream());
        out = new ObjectOutputStream(clientedConnected.getOutputStream());




                } catch (IOException ex) {
        Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("End of method Run");
} }

this is the output i get when i create run the server: 这是我创建运行服务器时得到的输出:

 server opened on port 7777
 method run started
 Waiting for a client to connect

client android: class to connect to my server( atm i just want it to receive the message): 客户端android:连接到我的服务器的类(atm我只希望它接收消息):

 import java.io.IOException;
  import java.io.ObjectInputStream;
  import java.io.ObjectOutputStream;
  import java.io.OptionalDataException;
 import java.net.Socket;
 import java.net.UnknownHostException;

 import android.util.Log;
 import android.view.View;
 import android.widget.TextView;

public class MyConnect implements Runnable{

private Socket myconnect=null ;
private TextView txtMessage;
private ObjectInputStream in; 
private ObjectOutputStream out;
public MyConnect( ){
    try {
        // this is my pc's IP, my phone is connected to same LAN
        Log.d("inizializating socket","");
        myconnect= new Socket("192.168.1.8",7777);
        in = new ObjectInputStream(myconnect.getInputStream());
        out = new ObjectOutputStream(myconnect.getOutputStream());
    } catch (UnknownHostException e) {
        Log.d("My Error connecting",e.getMessage());
    } catch (IOException e) {
        Log.d("My Error connecting",e.getMessage());
    }
 }
 @Override
 public void run() {
        try {
            String message = (String)in.readObject();
            Log.d("messaged recived",message);
        } catch (OptionalDataException e) {             
            Log.d("My Error connecting",e.getMessage());
        } catch (ClassNotFoundException e) {
            Log.d("Error My ClassNotFoundException",e.getMessage());
        } catch (IOException e) {
            Log.d("Error My IOEXCEPTION",e.getMessage());
        }





  }

 }

this is the error that i get when i click on a button that should create the socket: on create i use connect= new MyConnect(); 这是我单击应创建套接字的按钮时遇到的错误:创建时我使用connect = new MyConnect(); and on onclick event i use: 和onclick事件上,我使用:

   @Override
   public void onClick(View v) {
    switch(v.getId()){
    case R.id.btnExample:


        new Thread(connect).start();

        break;


    }

}

error message : 错误信息 :

05-29 19:02:05.905: E/AndroidRuntime(6520): FATAL EXCEPTION: main
05-29 19:02:05.905: E/AndroidRuntime(6520):      android.os.NetworkOnMainThreadException
05-29 19:02:05.905: E/AndroidRuntime(6520):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
05-29 19:02:05.905: E/AndroidRuntime(6520):     at  libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-29 19:02:05.905: E/AndroidRuntime(6520):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-29 19:02:05.905: E/AndroidRuntime(6520):     at libcore.io.IoBridge.connect(IoBridge.java:112)
05-29 19:02:05.905: E/AndroidRuntime(6520):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
 05-29 19:02:05.905: E/AndroidRuntime(6520):    at    java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
05-29 19:02:05.905: E/AndroidRuntime(6520):     at java.net.Socket.startupSocket(Socket.java:566)
05-29 19:02:05.905: E/AndroidRuntime(6520):     at java.net.Socket.tryAllAddresses(Socket.java:127)

EDIT: 编辑:

class MySyncTask extends AsyncTask<Integer, Integer, String>{
    String advice;
@Override
protected String doInBackground(Integer... params) {

    try {
        s = new Socket("192.168.1.8",7777);
        Log.d("socket connected","");
         ObjectInputStream streamReader = new ObjectInputStream(s.getInputStream()); 

            advice = (String)streamReader.readObject();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        return "";
    }

protected void onPostExecute(String result) {
     txtMessage.setText("you got a message: " + advice);
}
protected void onPreExecute() {
   Log.d("my started","start");
}    

}

and i used 和我用

  MySyncTask asyncTask=new MySyncTask ();
     asyncTask.execute();

on onCreate() method but for some reason it is not connecting to my server 在onCreate()方法上,但是由于某种原因它未连接到我的服务器

LogCat with AsyncTask: 使用AsyncTask的LogCat:

05-29 19:46:21.900: D/my started(26169): start
05-29 19:46:22.020: D/libEGL(26169): loaded /system/lib/egl/l ibEGL_mali.so
05-29 19:46:22.030: D/libEGL(26169): loaded /system/lib/egl/libGLESv1_CM_mali.so
05-29 19:46:22.040: D/libEGL(26169): loaded /system/lib/egl/libGLESv2_mali.so
05-29 19:46:22.080: D/OpenGLRenderer(26169): Enabling debug mode 0

EDIT PROBLEM SOLVED 解决了编辑问题

after searching on internet why socket was not connecting i found someone who had a similar problem and i found the answer here Android Socket not being instantiated i had to initializate the socket first and then use connect 在Internet上搜索后,为什么套接字未连接,我发现有人遇到类似的问题,并且我在这里找到答案, 而未实例化Android套接字,所以我必须先初始化套接字,然后再使用connect

This is happening because you are trying to perform a networking operation on the main thread. 发生这种情况是因为您试图在主线程上执行网络操作。 This is bad design, you do not want to lock up the user interface while you run a process that can take long time to execute. 这是一个糟糕的设计,您不想在运行可能需要很长时间才能执行的过程时锁定用户界面。

Put your network method in an AsyncTask or Service . 将您的网络方法放在AsyncTaskService中

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

Like Eduardo points out, 就像爱德华多指出的那样,

NetworkOnMainThreadException NetworkOnMainThreadException

The exception that is thrown when an application attempts to perform a networking operation on its main thread. 当应用程序尝试在其主线程上执行联网操作时引发的异常。

Use Asynctask for your connection 使用Asynctask进行连接

Be sure to have 一定要有

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

into your AndroidManifest.xml 到您的AndroidManifest.xml

Have you set the proper permissions in the manifest? 您是否在清单中设置了适当的权限? If yes, is the phone on the same network as your PC (if they are on same wifi network is good)? 如果是,电话与PC是否在同一网络上(如果它们位于同一wifi网络上就可以了)? Try running through debugger and putting a break point. 尝试运行调试器并设置断点。

Here is a nice tutorial that explains client/server communication in android. 这是一个很好的教程,解释了android中的客户端/服务器通信。 http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/ http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/

Good luck -Raghu 祝你好运-Raghu

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

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