Java 客户端使用两个服务器

Java Client working with two servers

我正在尝试做一个同时从两个服务器读取数据的客户端,例如,客户端向两个服务器发送一个字符串,将其大写,然后将其发送回客户端。

客户端

public class Client {

public static void main(String[] args) {

     Connection c1 = new Connection("localhost", 2345, "example one");
     c1.start();

     Connection c2 = new Connection("localhost", 2346, "example two");
     c2.start();

服务器端

public class Connection implements Runnable {

private String host;
private int port;
private PrintWriter os;
private volatile boolean running = false;
private String stringToCap;

public Connection(String host, int port, String stringToCap) {
    this.host = host;
    this.port = port;
    this.stringToCap = stringToCap;
}

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) {
    stringToCap.toUpperCase();

            os.print(stringToCap);


        }}

但我似乎无法让服务器将现在大写的字符串打印回客户端。当我尝试上面的方法时,我什么也没得到,我是否也需要在服务器端使用 main 方法?

看来你是误会了。

您当前的代码只是一个名为 Connection 的具有 2 个线程的多线程应用程序,而不是真正的客户端和服务器应用程序。

请参考Java Tutorial, Custom Networking section.