0
我試圖做一個客戶端,從兩臺服務器同時讀取數據,例如,客戶端向兩臺服務器發送一個字符串,然後將其發送回客戶端。Java客戶端與兩臺服務器工作
客戶端
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);
}}
但我似乎無法獲得服務器打印回現在大寫字符串到客戶端。當我嘗試上述時,我什麼也得不到,我是否也需要服務器端的主要方法?
也許你正在嘗試捕獲一個IOException。嘗試通過e.printStackTrace()打印錯誤。 – Aaron
您沒有服務器。 Connection類是一個客戶端並連接到現有的服務器。你的服務器在哪裏?請閱讀有關套接字編程的更多信息:https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html – Aaron