我希望客戶端連接到多個服務器。即我希望我的客戶發送一個號碼到,該號碼將數字平方並將其回顯給客戶端。但是,我希望客戶端將此平方號碼發送到偵聽不同端口的第二臺服務器。將客戶端連接到Java中的多個服務器
我不知道如何實現這個功能,我可以通過線程做到這一點,或者我會打開第二個套接字server2
?
這是我的客戶的代碼。
import java.io.*;
import java.net.*;
public class ClientA {
public static void main(String[] args) {
String serverhost = "localhost";
int serverport = 6789;
Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;
try {
clientSocket = new Socket(serverhost, serverport);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverhost);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + serverhost);
} //end try
if (clientSocket == null || os == null || is == null) {
System.err.println("An error has occured, please restart.");
return;
} //end if
try {
while (true) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String keyboardInput = br.readLine();
os.writeBytes(keyboardInput + "\n");
int n = Integer.parseInt(keyboardInput);
if (n == 0) {
break;
}
String responseLine = is.readLine();
System.out.println("Server returns its square as: " + responseLine);
}
os.close();
is.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
} //end try
} //end main
} //end class
您是否需要在收到響應後保持與第一臺服務器的連接? – ddmps
@Pescis不,我不知道。 – user1896168