0
我的客戶機類應該從用戶接收10個整數輸入並將其發送到服務器。服務器應該接受這10個數字並對它們進行排序。然後它應該將數組發送回客戶端,客戶端應該打印它們。我的客戶端代碼:讀取和寫入int套接字編程數組,java
public class TCPClient {
public static void main(String[] args) throws UnknownHostException, IOException {
int arr[]=new int[10];
int arrFromServer[]=new int[10];
BufferedReader inFromUser= new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost",6786);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
for(int i=0;i<10;i++)
arr[i]=Integer.parseInt(inFromUser.readLine());
for(int i=0;i<10;i++)
outToServer.writeInt(arr[i]);
for(int i=0;i<10;i++)
arrFromServer[i]=Integer.parseInt(inFromServer.readLine());
for (int i = 0; i < arrFromServer.length; i++) {
System.out.println("From Server::"+arrFromServer[i]);
}
clientSocket.close();
}
}
我的服務器代碼:
public class TCPServer {
public static void main(String[] args) throws IOException {
int arrFromClient[]=new int[10];
ServerSocket welcomeSocket = new ServerSocket(6786);
while(true){
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
for(int i=0;i<10;i++)
{
arrFromClient[i]=Integer.parseInt(inFromClient.readLine());
}
Arrays.sort(arrFromClient);
for (int i = 0; i < arrFromClient.length; i++) {
outToClient.writeInt(arrFromClient[i]);
}
}
}
}
當我嘗試,直到我手動終止程序運行在客戶端不斷接受數字代碼。理想情況下,在10個輸入後,它應該去服務器和服務器應該給排序的數組。
上述代碼有什麼問題。任何幫助將不勝感激。提前致謝。
提示:write'Int'與read'Line'。 – Kayaman
我知道了:(我應該使用哪一個?我使用readLine讀取用戶輸入並將writeInt寫入服務器。這是錯誤的嗎? – Pepper
'writeInt'不寫一行,兩種方法都是解釋的在javadocs中,我推薦閱讀它們 – Kayaman