可以同时连接多台服务器的客户端程序

1xQ*_*1xQ 2 java sockets multithreading

我已经使用 JAVA 中的套接字编程编写了一个基本的服务器客户端程序。服务器是多线程的,可以同时接受多个客户端连接。然而,客户端不是多线程的。客户端可以从服务器上传、下载、读取、写入和删除文件。我在命令提示符窗口中运行程序,因此它们没有任何外部用户界面。到目前为止,我的程序运行良好。

我现在想让客户端多线程化,以便它可以同时连接到多个服务器。然后我希望客户端能够向服务器发送请求。客户端可以在它可能连接的许多服务器中选择将请求发送到哪个服务器。

考虑到这一点,我将客户端代码更改为具有多个线程。但我不知道如何在程序运行时在服务器之间进行选择。有没有办法在JAVA中随意切换线程(程序运行时),以便我可以选择哪个线程处理我的请求?

小智 5

这是一些如何做到这一点的骨架:

public class Client {

    public static void main(String[] args) {

         Connection w1 = new Connection("localhost", 2346);
         w1.start();

         Connection w2 = new Connection("localhost", 2346);
         w2.start();

         Connection w3 = new Connection("localhost", 2347);
         w3.start();

         w1.sendMessage("Hello ");
         w2.sendMessage("Coffee ");
         w1.sendMessage("world!");
         w2.sendMessage("break!");
         w3.sendMessage("Beer!");

         w1.terminate();
         w2.terminate();
         w3.terminate();
    }
}
Run Code Online (Sandbox Code Playgroud)

只要您不使用忙等待就可以处理新线程中的每个连接:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Connection implements Runnable {

    private String host;
    private int port;
    private PrintWriter os;

    private volatile boolean running = false;
    private ConcurrentLinkedQueue<String> queue;

    public Connection(String host, int port) {
        this.host = host;
        this.port = port;
        this.queue = new ConcurrentLinkedQueue<String>();
    };

    public void start() {
        try {
            this.os = new PrintWriter(new Socket(host, port).getOutputStream());
        } catch (IOException e) {
            return;
        }

        running = true;
        new Thread(this).start();
    }

    @Override
    public void run() {

        while(running) {
            // send messages in queue
            while(!queue.isEmpty()) {
                os.print(queue.poll());
            }
            // wait to be notified about new messages
            try {
                this.wait();
            } catch (InterruptedException e) {
                terminate();
            }
        }
    }

    public synchronized void sendMessage(String msg) {
        queue.add(msg);
        this.notify();
    }

    public void terminate() {
        running = false;
    }

    public boolean isRunning() {
        return running;
    }
}
Run Code Online (Sandbox Code Playgroud)