简体   繁体   English

Android-Java服务器和Android客户端

[英]Android - Java Server and android client

I have implemented a very, very simple Java server, which basically listens for all requests on port 8080 and writes them to the console. 我实现了一个非常非常简单的Java服务器,该服务器基本上侦听端口8080上的所有请求并将它们写入控制台。

My code works fine, once. 我的代码可以正常运行一次。 But for each app restart, the server will only take one request. 但是对于每次重新启动应用程序,服务器将仅接受一个请求。 Can anybody help me? 有谁能够帮助我?

Server code: 服务器代码:

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

I am using this client to post to my server: 我正在使用此客户端发布到我的服务器:

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", "user@gmail.com"));
        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;
    }

}

It'd be better to use something like Jetty or Tomcat if you are going to be doing any, marginally serious Java HTTP serving. 如果您要进行任何严重的Java HTTP服务,最好使用JettyTomcat之类的东西。

If you're going to insist on using HttpServer, not actually really know it, I suspect it has to do with the single-threaded nature of HttpServer in it's default configuration and the socket being kept open & waiting for a period of time after. 如果您要坚持使用HttpServer,但实际上并不真正知道它,我怀疑它与HttpServer的默认配置中的单线程性质有关,并且套接字保持打开状态并等待一段时间。 It may also be that you aren't correctly closing the HttpClient in your Android client, and so it keeps the connection open to the server and so the server is tied up waiting for that client. 也可能是因为您未正确关闭Android客户端中的HttpClient,因此它使服务器保持连接打开状态,因此服务器被捆绑在一起等待该客户端。

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

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