简体   繁体   English

服务器如何在不关闭的情况下接受来自客户端的多个请求?

[英]How can a server take more than one request from a client without shutting down?

I have implemented a 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 server restart, it will only take one request.但是对于每次服务器重启,它只需要一个请求。

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

}

I would start by decomposing the problem.我将从分解问题开始。 You will need to find (or build) components that can solve these problems:您需要找到(或构建)可以解决这些问题的组件:

Server side服务器端

  • Listen for network connections侦听网络连接
  • Read data from the network stream从网络流中读取数据
  • Parse JSON data解析 JSON 数据
  • Process JSON into a useful format [optional]将 JSON 处理为有用的格式 [可选]
  • Store data on disk在磁盘上存储数据
  • Read data from disk从磁盘读取数据
  • Send data back to the client over the network通过网络将数据发送回客户端

Android side安卓端

  • Connect to the server over the network通过网络连接到服务器
  • Send JSON data发送 JSON 数据
  • Request data from the server从服务器请求数据

There are many SO questions related to each of these.有许多与这些相关的 SO 问题。 If you have a specific question about one of these problems, please post it as a separate question.如果您对这些问题之一有具体问题,请将其作为单独的问题发布。

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

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