2013-10-04 48 views
1

我已经实现了一个非常非常简单的Java服务器,它基本上监听端口8080上的所有请求并将它们写入控制台。Android - Java服务器和Android客户端

我的代码工作正常,一次。但是,对于每次重新启动应用程序,服务器只会收到一个请求。 任何人都可以帮助我吗?

Server代码:

public class RunServer { 

    public static void main(String[] args) { 
     final int port = 8080; 
     final String path = "/android"; 
     try { 
      HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);  //Create the server to listen for incoming requests on the specified port 
      server.createContext(path, new HttpHandler() { //Set a handler for  incoming requests to the specific path 
       @Override 
       public void handle(HttpExchange arg0) throws IOException {  //This method is called when new requests are incoming 
          InputStreamReader isr = new  InputStreamReader(arg0.getRequestBody(),"utf-8"); 
          BufferedReader br = new BufferedReader(isr); 
          String query = br.readLine(); 

          System.out.print(query); 
       } });   
      server.setExecutor(null); //Default executor. Other executors may be  used to e.g. use a threadpool for handling concurrent incoming requests. 
      server.start(); //Start the server. 
     } catch (Exception e) { 
      e.printStackTrace(); 
     }  
    } 
} 

我使用这个客户端发布到我的服务器:

public class MyAsyncTask extends AsyncTask<String, String, Void>{ 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost("http://192.168.1.5:8080/android"); 
    String s; 
    @Override 
    protected Void doInBackground(String... params) { 
     // Building post parameters 
     // key and value pair 
     List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2); 
     nameValuePair.add(new BasicNameValuePair("email", "[email protected]")); 
     nameValuePair.add(new BasicNameValuePair("message", 
       "Hi, trying Android HTTP post!")); 

     // Url Encoding the POST parameters 
     try { 
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
     } catch (UnsupportedEncodingException e) { 
      // writing error to Log 
      e.printStackTrace(); 
     } 

     // Making HTTP Request 
     try { 
      HttpResponse response = httpClient.execute(httpPost); 

      // writing response to log 
      Log.d("Http Response:", response.toString()); 
     } catch (ClientProtocolException e) { 
      // writing exception to log 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // writing exception to log 
      e.printStackTrace(); 

     } 
     return null; 
    } 

} 

回答

1

它最好能够使用类似JettyTomcat如果你将要做任何微乎其微的Java HTTP服务。

如果你要坚持使用HttpServer,实际上并没有真正了解它,我怀疑它与HttpServer的单线程本质有关,它的默认配置和套接字保持打开状态&等待一段时间之后的时间。这也可能是因为你没有正确关闭你的Android客户端中的HttpClient,所以它保持连接对服务器开放,所以服务器被捆绑在等待该客户端。

+0

谢谢,我认为你对第一部分是正确的。我试图用tomcat设置它作为一个servlet,它现在看起来很完美! –

+0

如果您最终将其用于生产,请务必阅读文档的安全部分。如果你有一个现有的Java应用程序,也许考虑嵌入Jetty或Tomcat而不是独立。 – Drizzt321