0

I want to made a Server Which makes a client and start conversation with him but IOException is occur in Handler's code I couldn't underStand why Br.readLine method throws Exception Here is code of mine Server project's package's classess and two clients abc, def classes are also

This is code of Server projects classeess...............

        package server;
        import java.io.IOException;
        import java.net.ServerSocket;
        public class Server {
            private void operate() {
                try {
                    ServerSocket serverSocket = new ServerSocket(2222);
                    while(true) new Thread(new Handler(serverSocket.accept())).start();
                } catch(IOException e){
                    System.out.println("IOException in operate method of Server");
                }
            }    
            public static void main(String[] args) {
                new Server().operate();
            }
        }

package server;
import java.io.*;
import java.net.Socket;
public class Handler implements Runnable {
    Handler(Socket s) {
        socket = s;
        counter++;
    }
    public void run() {
        try {
            while(true) System.out.println(new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine());                 //This throw the IOExceptionnnnnnnnnnnnnnnnnnnnn...............
        } catch(IOException e) {
            System.out.println("IOException in "+counter+"'s run method");
        }
    }
    private final Socket socket; 
    private static int counter =0;
}

Code of First Client ABC...........................

package abc;
import java.net.Socket;
import java.io.*;
public class Abc {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost",2222);
            while(true) new PrintWriter(socket.getOutputStream()).println("HI from Abc");
        } catch(IOException e) {
            System.out.println("IOException in main ");
        }
    }
}

Code of Another Client DEf.........................

package def;
import java.io.*;
import java.net.Socket;
public class DEf {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost",2222);
            while(true) new PrintWriter(socket.getOutputStream()).println("HI from Abc");
        } catch(IOException e) {
            System.out.println("IOException in main ");
        }
    }
}
Zohaib
  • 19
  • 6

2 Answers2

0

Your clients request the output stream repeatedly from the socket using socket.getOutputStream(). Instead, you should invoke this method and create a corresponding writer only once, for example:

Socket socket = new Socket("localhost",2222);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
while(true) {
  writer.println("HI from Abc");
  ...
}

Same with the Handler class - create your buffered reader once.

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
0

I have already posted answers on Server-Client Socket Communication. Please have a look.


Try this code. It might solve you problem.

Handler.java:

  • Check BufferedReader.ready() before BufferedReader.readLine()

  • Use single BufferedReader

    class Handler implements Runnable {
        private BufferedReader reader;
    
        Handler(Socket s) {
            socket = s;
            counter++;
            try {
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public void run() {
            try {
                while (socket.isConnected() && !socket.isClosed()) {
                    if(!reader.ready()){
                        continue;
                    }
                    //System.out.println("ready");
                    System.out.println(reader.readLine()); // This throw
                                                           // the
                } // IOExceptionnnnnnnnnnnnnnnnnnnnn...............
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("IOException in " + counter + "'s run method");
            }
        }
    
        private final Socket socket;
        private static int counter = 0;
    }
    

Abc.java:

  • Use single PrintWriter

        PrintWriter writer = new PrintWriter(socket.getOutputStream());
        while (true)
            writer.println("HI from Abc");
    

DEf.java:

  • Use single PrintWriter

        PrintWriter writer = new PrintWriter(socket.getOutputStream());
        while (true)
            writer.println("HI from Abc");
    
Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • Please let me know, if problem is still not resolved? – Braj Mar 17 '14 at 12:41
  • Are you getting this exception `java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:168)` when any client is disconnected from server. – Braj Mar 17 '14 at 12:41
  • Thanks,,,,,,,, and new problem is Result in continous run of server even if client stop – Zohaib Mar 17 '14 at 13:20
  • Just un-comment `if(!reader.ready()){ continue; }` Let me update it in code. – Braj Mar 17 '14 at 13:21
  • I have updated the code. Now try it again. `reader.ready()` will solve you problem. – Braj Mar 17 '14 at 13:22
  • Sorry, I missed one more thing `socket.isConnected() && !socket.isClosed()`. I have updated it also. – Braj Mar 17 '14 at 13:30
  • Let me know whether it working or not? Your next problem *Result in continous run of server even if client stop.* is solved by this. – Braj Mar 17 '14 at 13:31
  • Now not even statement is reading by System.out.println(reader.readLine()); Just Continue running both Client and Server..... Without any System.out – Zohaib Mar 17 '14 at 14:12
  • Please check it again. Its working as expected. Whenever any client is added to server then server starts to print message in infinite loop but as soon as client is closed, server also stops to print it. It comes out of `while` loop as condition that I have mentioned in my answer returns false when client is disconnected. – Braj Mar 17 '14 at 14:15
  • But Client programme ABc, DEf are not stopped even if Server Stop – Zohaib Mar 17 '14 at 14:20
  • OK the problem is with stopping server. Let me check it. I have tested for Client. – Braj Mar 17 '14 at 14:21
  • You have to send some message from server to client on server stop and client will read it and come out of `while` loop and close the `socket` as well as `writer`. Is this code part of GUI application then add `addWindowListener` on `Window`. – Braj Mar 17 '14 at 14:50
  • I have already shared a code for server client chat in my other posts. – Braj Mar 17 '14 at 14:52
  • Yes I Have Reading it ... trying to understand.... It will be Great help full because i am new to io and multithreading – Zohaib Mar 17 '14 at 14:54