1
votes

Below is the code where there is a server to accept multiple client connections and respond. The server is able to receive the client's message but client is not receiving server messages. I have used multi threading concept on the server. I also observed that nothing works (even a println statement) beyond line marked with ####. Could be that client is blocked.. Any thoughts? server code: public static void main(String argv[]) throws Exception {

     ServerSocket welcomeSocket = new ServerSocket(10000);

     while(true)
     {

        Socket connectionSocket = welcomeSocket.accept(); 

        Thread t = new Thread(new acceptconnection(connectionSocket));
        t.start();}}


   class acceptconnection implements Runnable{
            BufferedReader inFromClient,inn;
                DataOutputStream ds;
             Socket clientsocket;
        //constructor
        acceptconnection (Socket socket) throws IOException{
        this.clientsocket = socket;
        inn = new BufferedReader (new InputStreamReader(System.in));
        inFromClient =new BufferedReader(new  InputStreamReader(clientsocket.getInputStream()));
        ds = new DataOutputStream(clientsocket.getOutputStream());

         public void run (){
         try {
        String clientSentence, inp;
         while(( clientSentence = inFromClient.readLine())!=null)
         {
               System.out.println("from client" + clientSentence);
               ds.writeBytes("hi from server");**// THIS DOES NOT WORK**
         }

    }


  Client code:

     public static void main(String argv[]) throws Exception
   {

  Socket clientSocket;
   while(true)
  {
   // clientSock
    clientSocket = new Socket("localhost", 10000);
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));

  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new    InputStreamReader(clientSocket.getInputStream()));

  System.out.println("Enter something:"); 
  sentence = inFromUser.readLine();  
  outToServer.writeBytes(sentence + '\n');// THIS WORKS - thats why server receives it

  **####** modifiedSentence = inFromServer.readLine();**// THIS DOES NOT WORK -client unable to receive** 

  System.out.println("FROM SERVER: " + modifiedSentence + "remote sock add: "+      clientSocket.getRemoteSocketAddress());
2
You might compare your code with this working example.trashgod

2 Answers

1
votes

As you're using BufferedReader.readLine() in your client, make sure to use a newline character when writing data out:

ds.writeBytes("hi from server\n"); 

And, as stated already, remember to flush...

ds.flush();
1
votes

You should flush the stream on the server side

 ds.writeBytes("hello world".getBytes());
 ds.flush();