java - 客户端服务器程序的多线程

标签 java multithreading sockets client-server

我正在尝试使用我一直在开发的客户端/服务器程序来实现多线程。我需要允许多个客户端同时连接到服务器。我目前有 4 个类:一个客户端、一个服务器、一个协议(protocol)和一个处理线程的工作人员。以下代码是我为这些类编写的代码:

SocketServer 类:

public class SocketServer {


     public static void main(String[] args) throws IOException {

        int portNumber = 9987;

        try ( 
            ServerSocket serverSocket = new ServerSocket(portNumber);
            Socket clientSocket = serverSocket.accept();
            PrintWriter out =
                new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));

        ) {
            Thread thread = new Thread(new ClientWorker(clientSocket));
            thread.start(); //start thread

            String inputLine, outputLine;

            // Initiate conversation with client
            Protocol prot = new Protocol();
            outputLine = prot.processInput(null);
            out.println(outputLine);

            while ((inputLine = in.readLine()) != null) {
                outputLine = prot.processInput(inputLine);
                out.println(outputLine);
                if (outputLine.equals("quit"))
                    break;
            }
        } catch (IOException e) {
            System.out.println("Exception caught when trying to listen on port "
                + portNumber + " or listening for a connection");
            System.out.println(e.getMessage());
        }
    }
}

SocketClient 类:

public class SocketClient {
     public static void main(String[] args) throws IOException 
    {

        String hostName = "localhost";
        int portNumber = 9987;

        try (
            Socket socket = new Socket(hostName, portNumber);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
        ) {
            BufferedReader stdIn =
            new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;

            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("quit"))
                    break;

                fromUser = stdIn.readLine();
                if (fromUser != null) {
                    System.out.println("Client: " + fromUser);
                    out.println(fromUser);
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        }
    }
}

协议(protocol)类:

public class Protocol {

    private static final int waiting         = 0;
    private static final int sentPrompt      = 1;


    private int status = waiting;

     public String processInput(String theInput) {
         String theOutput = null;

        if (status == waiting) {
            theOutput = "Please enter what you would like to retrieve: 'customer' or 'product' ";
            status = sentPrompt;
        }
        else if ( status == sentPrompt ) {
            if ( theInput.equalsIgnoreCase("product")) {
                File f = new File("product.txt");
                Scanner sc = null;
                try {
                    sc = new Scanner(f);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
                }

                while ( sc.hasNextLine()  ) {
                    String line   = sc.nextLine();
                    theOutput = "The current product entries are : " + line;
                }
                return theOutput;
            }
            else if ( theInput.equalsIgnoreCase("customer")) {
                File f = new File("customer.txt");
                Scanner sc = null;
                try {
                    sc = new Scanner(f);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
                }

                while ( sc.hasNextLine()  ) {
                    String line   = sc.nextLine();
                    theOutput = "The current customer entries are : " + line;
                }
                return theOutput;

            }
            else if ( theInput.equalsIgnoreCase("quit")) {
                return "quit";
            }
            else {
                return "quit";
            }
        }
        return theOutput;
    }
}

ClientWorker 类:

public class ClientWorker implements Runnable {
    private final Socket client;

    public ClientWorker( Socket client ) {
        this.client = client;
    }

    @Override
    public void run() {
        String line;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            System.out.println("Thread started with name:"+Thread.currentThread().getName());
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            out = new PrintWriter(client.getOutputStream(), true);
        } catch (IOException e) {
            System.out.println("in or out failed");
            System.exit(-1);
        }

        while (true) {
            try {
                System.out.println("Thread running with name:"+Thread.currentThread().getName());
                line = in.readLine();
                //Send data back to client
                out.println(line);
                //Append data to text area
            } catch (IOException e) {
                System.out.println("Read failed");
                System.exit(-1);
            }
        }
    }       
}

当我运行服务器和客户端时,一切都按预期正常工作。然后,当我尝试运行另一个客户端时,它只是卡在那里并且不会提示客户端给出响应。非常感谢任何对我所缺少的内容的见解!

最佳答案

您的服务器代码应解决以下功能的实现。

  1. 继续接受来自 ServerSocket 的套接字在 while 循环中

  2. 在accept()调用后通过传递客户端套接字创建新线程,即Socket

  3. 在客户端套接字线程中进行 IO 处理,例如您的情况下的 ClientWorker

看看这个 article

你的代码应该是

ServerSocket serverSocket = new ServerSocket(portNumber);
while(true){
  try{
    Socket clientSocket = serverSocket.accept();
    Thread thread = new ClientWorker(clientSocket);
    thread.start(); //start thread
  }catch(Exception err){
     err.printStackTrace();
  }
}

关于java - 客户端服务器程序的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33087890/

相关文章:

java - Jsf 属性未保存

java - 不幸的是应用程序已在 Eclipse 中停止

java - JdbcTemplate.update() 插入返回值

JavaFX ComboBox - 如何获取不同的提示文本和所选项目文本?

java - 卡在PostgreSQL上的多线程数据处理

javascript - 使用 Socket.io 有效发送大数组坐标

java - 限制 Java 中的线程执行处理器周期

c# - 是否会按照严格的时间顺序调用 GTK+ 超时回调?

c++ - 发送没有文件描述符的文件

java - DatagramSocket.receive() 问题