0

我正在尝试在 android 中创建一个简单的多线程服务器,我正在使用的代码没有给我任何错误,但是警告请查看我的代码并告诉错误,如果将其作为 java 运行,我的代码可以正常工作应用程序代码如下:

 package dolphin.developers.com;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;


public   class AnroidWebServerActivity extends Activity  {
     ServerSocket serverSocket;

{





    try {

        runserver();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
    public void runserver() throws Exception {


        serverSocket = new ServerSocket(8080);
        acceptRequest();

    }

    private void acceptRequest() throws Exception{

        while(true){

            Socket s = serverSocket.accept();
            Log.v("tag", "server is ruunning!!");

            ConnectionHandler ch = new ConnectionHandler(s);
            ch.start();
        }

    }


       public class ConnectionHandler extends Thread {

           PrintWriter pw;
           BufferedReader br;

           Socket s;
           public ConnectionHandler(Socket s) throws Exception{
               this.s = s;

               br = new BufferedReader(new InputStreamReader(s.getInputStream()));
               pw = new PrintWriter(s.getOutputStream());



           }

           @Override
        public void run() {
             Looper.loop();
               try{

               String reqS = "";


               while (br.ready() || reqS.length() == 0){

                   reqS += (char) br.read();
        }

               System.out.println(reqS);

               HttpRequest req = new HttpRequest(reqS);
               HttpResponse res = new HttpResponse(req);


               pw.write(res.response.toCharArray());
               pw.close();
               br.close();
               s.close();


               }
               catch (Exception e) {
                   e.printStackTrace(); 
                   }
               }


       }


       public class HttpRequest{
           public String filename ;

        public HttpRequest(String request){

               String lines[] = request.split("\n");
               lines = lines[0].split(" ");
               filename = lines[1];


           } 

       }
             public class HttpResponse{

                 HttpRequest req;

                 String root;

                 String response;

                 public HttpResponse(HttpRequest request){
                     req=request;

                     root = Environment.getExternalStorageDirectory() + "/";

                     File f  = new File(root + req.filename);


                     try{


                     response+= "HTTP/1.1 200 \r\n";
                     response+= "Apache Server /1.0";
                     response+= "Content-Type: text/html \r\n";
                     response+="Connection: close \r\n";
                     response+= "Content-Length:" + f.length() + "\r\n";
                     response+= "\r\n";

                     FileInputStream fis = new FileInputStream(f);


                     int s;

                     while ((s = fis.read()) != -1){

                         response += (char)s ;


                     }

                     fis.close(); 


                 }catch(FileNotFoundException fg){
                     response = response.replace("200", "404");

                 }

                     catch(IOException e ){

                         response  = response.replace("200", "500");

                         e.printStackTrace();
                     }
             }

}

}

日志猫:

07-18 14:34:23.367: W/System.err(1249): android.os.NetworkOnMainThreadException
07-18 14:34:23.388: W/System.err(1249):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
07-18 14:34:23.398: W/System.err(1249):     at libcore.io.BlockGuardOs.accept(BlockGuardOs.java:54)
07-18 14:34:23.398: W/System.err(1249):     at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:98)
07-18 14:34:23.398: W/System.err(1249):     at java.net.ServerSocket.implAccept(ServerSocket.java:202)
07-18 14:34:23.398: W/System.err(1249):     at java.net.ServerSocket.accept(ServerSocket.java:127)
07-18 14:34:23.407: W/System.err(1249):     at dolphin.developers.com.AnroidWebServerActivity.acceptRequest(AnroidWebServerActivity.java:47)
07-18 14:34:23.407: W/System.err(1249):     at dolphin.developers.com.AnroidWebServerActivity.runserver(AnroidWebServerActivity.java:40)
07-18 14:34:23.407: W/System.err(1249):     at dolphin.developers.com.AnroidWebServerActivity.<init>(AnroidWebServerActivity.java:30)
07-18 14:34:23.407: W/System.err(1249):     at java.lang.Class.newInstanceImpl(Native Method)
07-18 14:34:23.407: W/System.err(1249):     at java.lang.Class.newInstance(Class.java:1319)
07-18 14:34:23.407: W/System.err(1249):     at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
07-18 14:34:23.407: W/System.err(1249):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
07-18 14:34:23.407: W/System.err(1249):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-18 14:34:23.407: W/System.err(1249):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-18 14:34:23.407: W/System.err(1249):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-18 14:34:23.427: W/System.err(1249):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-18 14:34:23.447: W/System.err(1249):     at android.os.Looper.loop(Looper.java:137)
07-18 14:34:23.447: W/System.err(1249):     at android.app.ActivityThread.main(ActivityThread.java:5039)
07-18 14:34:23.447: W/System.err(1249):     at java.lang.reflect.Method.invokeNative(Native Method)
07-18 14:34:23.447: W/System.err(1249):     at java.lang.reflect.Method.invoke(Method.java:511)
07-18 14:34:23.447: W/System.err(1249):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-18 14:34:23.447: W/System.err(1249):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-18 14:34:23.447: W/System.err(1249):     at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

2

看起来您正试图直接从 Activity 的主线程运行服务器。这将阻止您的应用程序运行并最终导致它崩溃。您需要在后台线程上运行服务器。

正确的方法是将您的服务器线程移动到服务中,您可以在此处阅读更多信息:http: //developer.android.com/training/run-background-service/index.html。本文将为您提供一些直接在 Activity 中使用线程的其他选项:http ://www.vogella.com/articles/AndroidBackgroundProcessing/article.html 。

于 2013-07-18T15:08:39.813 回答