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

时间:2014-02-24 01:25:18

标签: java multithreading sockets

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

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

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

1 个答案:

答案 0 :(得分:4)

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

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

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

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;
    }
}
相关问题