My client class should take 10 integer input from user and send it to the server. The server should accept these 10 numbers and sort them. It should then send the array back to the client and the client should print them. My client code is:
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();
}
}
My server code is:
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]);
}
}
}
}
When I try to run the code the client keeps on accepting numbers until I terminate the program manually. Ideally after 10 inputs it should go to the server and server should give the sorted array.
What is wrong with the above code. Any help will be appreciated. Thanks in advance.
Intvs. readLine.writeIntdoesn't write a line. Both methods are explained in the javadocs, I recommend reading them.readLine()to read whatwriteInt()writes.