2

i have client server socket programming in java .

Server: Multi-threading server to serve the client for math calculations ,eg: sum of all numbers provided from client etc....

client: is to connect to the server and select specif math operations addition,subtraction ... etc ,and provide the numbers to the server to return the result,and maybe the results is single value or maybe the result from server is array of numbers and depends on the type of the operation...

my Problem is: reading and writing blocking from server to client and vice-versa eg:

**server->client :*** Welcome to the Calculation Server
server->client: "*** Please type in the num of rows: \n"
client->server: the user insert num of rows and send it to server
server->client: "*** Please type in the num of cols: \n"
client->server: the user insert num of columns and send it to server
server->client:writer.write("Enter the elements of first matrix");
client->server: at the client side it blocks or hang i dont know y???**

the server send

part of server code

import java.net.*; 
import java.io.*; 

class server_thread extends Thread
{ 
 protected Socket clientSocket;

 public static void main(String[] args) throws IOException 
   { 
    ServerSocket serverSocket = null; 
    int port=10008;
    try { 
         serverSocket = new ServerSocket(port); 
         System.out.println ("Connection Socket Created on port : "+port);
         try { 
              while (true)
                 {
                  System.out.println ("Waiting for Connection");
                  new server_thread (serverSocket.accept()); 
                 }
             } 
         catch (IOException e) 
             { 
              System.err.println("Accept failed."); 
              System.exit(1); 
             } 
        } 
    catch (IOException e) 
        { 
         System.err.println("Could not listen on port: 10008."); 
         System.exit(1); 
        } 
    finally
        {
         try {
              serverSocket.close(); 
             }
         catch (IOException e)
             { 
              System.err.println("Could not close port: 10008."); 
              System.exit(1); 
             } 
        }
   }

 private server_thread (Socket clientSoc)
   {
    clientSocket = clientSoc;
    start();
   }

 public void run()
   {
    System.out.println ("New Communication Thread Started");

    try { 
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter writer= 
                    new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

    String sinput_row, sinput_col,srow_count, scol_count;
    int row_count, col_count;

            writer.write("*** Welcome to the Calculation Server ( ***\r\n");            




 ////////////////////////////////////////////////////////////////////////////////////////////////
              writer.write("*** Please type in the num of rows: \n");
              writer.flush();
              sinput_row = reader.readLine().trim();
              int input_row=Integer.parseInt(sinput_row);
              System.out.println("num of rows got:"+input_row); 

 //////////////////////////////////////////////////////////////////////////////////////////////////////



 ////////////////////////////////////////////////////////////////////////////////////////////////
              writer.write("*** Please type in the num of cols: \n");
              writer.flush();
              sinput_col = reader.readLine().trim();
              int input_col=Integer.parseInt(sinput_col);
              System.out.println("num of Cols got:"+input_col); 

 //////////////////////////////////////////////////////////////////////////////////////////////////////


  ////////////////////////////////////////////////////////////////////////////////////////////////

  writer.write("Enter the elements of first matrix");
  writer.flush();

   int first[][] = new int[input_row][input_col];
      int second[][] = new int[input_row][input_col];
      int sum[][] = new int[input_row][input_col];

      for (  row_count = 0 ; row_count < input_row ; row_count++ )
         for ( col_count = 0 ; col_count < input_col ; col_count++ )
         {
             String s_matrix1_element=reader.readLine().trim();
             int matrix1_element=Integer.parseInt(s_matrix1_element);
            first[row_count][col_count] = matrix1_element; 

         }


  // the rest of code is ommited for simplicty of analysis

   ////////////////////////////////////////////////////////////////////////////////////////////////


            //int result=num1+num2;            
            System.out.println("Addition operation done " );

             writer.flush();
             writer.write("");

            //writer.write("\r\n=== Result is  : "+result);
            writer.flush();
            clientSocket.close();
        } 
    catch (IOException e) 
        { 
         System.err.println("Problem with Communication Server");
         System.exit(1); 
        } 
    }
} 

and here is client code :

import java.io.*;
import java.net.*;
import java.util.*;

public class client_thread {

   public static void main(String argv[])
      {
       try{
            Socket socketClient= new Socket("localhost",10008);
            System.out.println("Client: "+"Connection Established");

            BufferedReader reader = 
                    new BufferedReader(new InputStreamReader(socketClient.getInputStream()));

            BufferedWriter writer= 
                    new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));

            BufferedReader stdIn = new BufferedReader(
                                   new InputStreamReader(System.in));
            String serverMsg;
            String userInput;

            writer.flush();
            serverMsg = reader.readLine();
            System.out.println("from server: " + serverMsg);
            while((serverMsg = reader.readLine()) != null   )
            {


                System.out.println("from server inside loop: " + serverMsg);

                userInput = stdIn.readLine();
                 writer.write(userInput+"\r\n");
                  writer.flush();


            }

       }catch(Exception e){e.printStackTrace();}
      }
}

so the problem

2
  • It's called blocking IO for a reason. Commented Nov 9, 2014 at 10:12
  • Can you check with a debugger at what line exactly it "hangs"? And show us the exact user input? Commented Nov 9, 2014 at 10:31

2 Answers 2

1

Your server writes:

writer.write("Enter the elements of first matrix");

And the client reads this using

while((serverMsg = reader.readLine()) != null)

So, since the server doesn't send any end of line, the clients waits for it.

Sign up to request clarification or add additional context in comments.

Comments

0

Method 1: Use 1 thread to handle your input stream and another thread to handle your output stream. Then you can do you read and write concurrently.

Method 2: Use NIO (Non Blocking I/O).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.