【问题标题】:Extend server code so server is able to interact wit clients using multithreading.So the no of clients sim connected the same server扩展服务器代码,以便服务器能够使用多线程与客户端进行交互。因此,没有客户端 sim 连接同一台服务器
【发布时间】:2016-11-08 11:30:05
【问题描述】:

*无法弄清楚上面的问题。已经尝试过oracle教程并注意但是我仍然无法做到。任何帮助将不胜感激。

Blackboard上给出的权重转换服务器(ConversionServerNoConcurrency.java)可以与多个交互 客户端,但只能以顺序方式(即新客户端实例只有在服务器连接 完成与前一个客户的交易)。 扩展/修改给定的服务器代码,以便服务器能够与多个客户端并行(同时)交互, 使用多线程。不应限制同时连接到同一台服务器的客户端数量。

确实需要一些代码方面的帮助,否则我在做作业时将无法暗示它

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ConversionServerNoConcurrency {
private Socket s;
private Scanner in;
private PrintWriter out;
public static void main(String[] args) throws IOException {

    ServerSocket server = new ServerSocket(8888);

    ConversionServerNoConcurrency serverInstance = new         ConversionServerNoConcurrency();

    System.out.println("Server running. Waiting for a client to connect...");

    while (true) {

        serverInstance.s = server.accept();

        System.out.println("Client connected");

        serverInstance.run();

        System.out.println("Client disconnected. Waiting for a new client to connect...");
    }
}
public void run() {
    try {
        try {

            in = new Scanner(s.getInputStream());

            out = new PrintWriter(s.getOutputStream());

            doService(); 

        } finally {
            s.close();
        }
    } catch (IOException e) {
        System.err.println(e);
    }
}
public void doService() throws IOException {

    while (true) {

        if (!in.hasNext())
            return;

        String request = in.next();

        System.out.println("Request received from client: \'" + request + "\'");

        if (!request.equals("QUIT")) // end connection with this client 
            handleConversionRequest(request);

    }
}
public void handleConversionRequest(String request) {

    String amountStr = in.next();

    double amount = Double.valueOf(amountStr);

    System.out.println("Amount received from client: " + amount);

    if (request.equals("CONVERT_TO_POUNDS")) {
        out.println(amount * 2.2d); // send conversion result to client
        System.out.println("Sent conversion result to client");
    } else if (request.equals("CONVERT_TO_KGS")) {
        out.println(amount / 2.2d); 
        System.out.println("Sent conversion result to client");
    } else
        System.err.println("Unknown request!");

       out.flush();
     }
}

 

import java.io.*;
import java.net.Socket;
import java.util.Scanner;


public class ConversionClient {

    public static void main(String[] args) throws IOException, InterruptedException{
        Socket s = new Socket("localhost", 8888);
        InputStream instream= s.getInputStream();
        OutputStream outstream= s.getOutputStream();
        Scanner in = new Scanner(instream);
        PrintWriter out = new PrintWriter(outstream);
        out.print("CONVERT_TO_KGS 123.45\n");  // we send the 1st request to the server
        out.flush();
        String response = in.nextLine();
        System.out.println("Received from server: " + response);
        Thread.sleep(2000); // delay the next request a bit
        out.print("CONVERT_TO_POUNDS 56\n");  // 2nd request
        out.flush();
        response = in.nextLine();
        System.out.println("Received from server: " + response);
        Thread.sleep(2000); // delay the next request a bit
        out.print("CONVERT_TO_POUNDS 836.98\n");  // 3rd request
        out.flush();
        response = in.nextLine();
        System.out.println("Received from server: " + response);
        out.print("QUIT\n");  
        out.flush();
        s.close();
    }

}

【问题讨论】:

  • 即使在这个站点上也有成千上万的多线程服务器示例。

标签: java multithreading


【解决方案1】:

编写面向并发连接的服务器是计算机科学/软件工程中的一门重要学科。因此,即使您不知道如何编码,您也必须了解以下内容。

  1. 在像ConversionServerNoConcurrency 这样的迭代式面向连接服务器中,它将只有一个线程(主线程)接收连接和服务连接。
  2. 如果您想开发面向并发连接的服务器,您需要将接收连接和服务连接分成两个不同的线程。
  3. 如果您在下面看到ConversionServerConcurrency,则连接接收由主线程完成,并将连接服务委托给execService 池中的线程。使用线程池来避免 DDoS 攻击很重要。因为在线程池中,可以生成的线程数量有一个最大限制。
  4. 看看ConversionServerTask,它现在拥有服务连接的所有逻辑。

    import java.io.*;
    import java.net.*;
    import java.util.Scanner;
    import java.util.concurrent.*;
    public class ConversionServerConcurrency {
    
    public static void main(String[] args) throws IOException {
    
        ServerSocket server = new ServerSocket(8888);
    
        System.out.println("Server running. Waiting for a client to connect...");
    
        ExecutorService execService = Executors.newFixedThreadPool(10);
    
        while (true) {
    
            Socket clientSocket = server.accept();
    
            execService.submit(new ConversionServerTask(clientSocket));
    
            System.out.println("Waiting for a new client to connect...");
        }
    }
    
    public static class ConversionServerTask implements Runnable {
        private Socket s;
        private Scanner in;
        private PrintWriter out;
    
        public ConversionServerTask(Socket clientSocket) {
            this.s = clientSocket;
        }
    
    
        public void run() {
            System.out.println("Client connected");
            try {
                try {
    
                    in = new Scanner(s.getInputStream());
    
                    out = new PrintWriter(s.getOutputStream());
    
                    doService();
    
                } finally {
                    s.close();
                }
            } catch (IOException e) {
                System.err.println(e);
            } finally {
                System.out.println("Client disconnected");
            }
        }
        public void doService() throws IOException {
    
            while (true) {
    
                if (!in.hasNext())
                    return;
    
                String request = in.next();
    
                System.out.println("Request received from client: \'" + request + "\'");
    
                if (request.equals("QUIT")) {// end connection with this client 
                    break;
                } else {
                    handleConversionRequest(request);
                }
    
            }
        }
        public void handleConversionRequest(String request) {
    
            String amountStr = in.next();
    
            double amount = Double.valueOf(amountStr);
    
            System.out.println("Amount received from client: " + amount);
    
            if (request.equals("CONVERT_TO_POUNDS")) {
                out.println(amount * 2.2d); // send conversion result to client
                System.out.println("Sent conversion result to client");
            } else if (request.equals("CONVERT_TO_KGS")) {
                out.println(amount / 2.2d);
                System.out.println("Sent conversion result to client");
            } else
                System.err.println("Unknown request!");
    
            out.flush();
        }
    }
    
    
    }
    

【讨论】:

  • 你必须有 Java 版本 1.7+
猜你喜欢
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 2015-12-25
  • 2014-12-21
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多