简体   繁体   English

在JAVA中将单线程服务器转换为多线程

[英]Convert Single Threaded Server into Multi Threaded in JAVA

I need to convert this single threaded Server in Multi Threaded one, so i'm able to handle multiple request from a server: 我需要将这个单线程服务器转换为多线程服务器,所以我能够处理来自服务器的多个请求:

public class YASGP {
    public static void main(String args[]) throws IOException {
        ServerSocket server;
        try{
            server = new ServerSocket(5559);

        System.out.println("Listening for connection on port 5559 ....");

        while (true) {
            Socket clientSocket = server.accept();
            InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            String line = reader.readLine();
            new Thread(new WorkerRunnable(clientSocket)).start();
            while (!line.isEmpty()) {
                System.out.println("----- " + line);
                if (!line.contains("OPTIONS")) {
                    //  System.out.println("Non c'è nulla!!!");
                } else {
                    timeS = line.substring(line.indexOf("timeS=") + 6, line.indexOf("&url"));
                    url = line.substring(line.indexOf("url=") + 4, line.lastIndexOf("&param"));
                    param = line.substring(line.indexOf("&param=") + 7, line.indexOf("HTTP"));
                }
                line = reader.readLine();
            }
            } 
        }
    }catch (IOException e) {
        System.out.println("Could not listen on port: 4001");
}
}
private static class RequestHandlingClass {
        public RequestHandlingClass(Socket clientSocket) {
        }
    }
}

How i can convert it? 我该如何转换? Thanks to all 谢谢大家

remove the 'client processing' code from the server as follows 如下所示从服务器中删除“客户端处理”代码

    public static void main(String args[]) throws IOException {
        ServerSocket server;
        try{
            server = new ServerSocket(5559);
            System.out.println("Listening for connection on port 5559 ....");

            while (true) {
                Socket clientSocket = server.accept();
                new Thread(new WorkerRunnable(clientSocket)).start();
            }

        }catch (IOException e) {
            System.out.println("Could not listen on port: 4001");
        }
    }

then the code that you lifted out goes in to the run method of the workerRunnable class . 然后您取出的代码将进入workerRunnable类的run方法。

I recommend u use the excutorService api.Since it will manager all your threading issue for u behind the scene 我建议您使用excutorService API,因为它将在后台为您解决所有线程问题

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
  //Your code here
});

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

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