I'm asking out of a "this can't be right" kind of mindset. This is the Code I'm trying to write:
final Socket client; // Constructor public ClientHandler(Socket client) { this.client = client; } @Override public void run() { // Instantiating Readers and Writers InputStreamReader binaryReader; //for primitive Datatypes DataOutputStream binaryWriter; //for primitive Datatypes BufferedReader asciiReader; //for ASCII Strings PrintWriter asciiWriter; //for ASCII Strings // Assigning Readers and Writers boolean IOInitialized = false; while (!IOInitialized) { try { binaryReader = new InputStreamReader(client.getInputStream()); binaryWriter = new DataOutputStream(client.getOutputStream()); asciiReader = new BufferedReader(binaryReader); asciiWriter = new PrintWriter(client.getOutputStream()); IOInitialized = true; } catch (IOException ex) { ex.printStackTrace(); } } //Testing asciiWriter.println("Testing Writer"); } I'm trying to initialize IOStreams from a Socket. Their initialisation requires a Try-Catch block, and using the new IOStreams requires a guarantee that they're initialized, which I solved with the while loop but the compiler doesn't accept this. When trying to use the asciiWriter to print something to the Client, the compiler tells me that "asciiWriter might not have been initialized". Encompassing the entire run()-method would solve the problem but seems like a very unclean solution. Is there any way I can get this to work in a better way?
binaryReaderandasciiReader, have aReadertype for Unicode character data and nothing else, not “for primitive Datatypes” and not limited to ASCII in any way. The only difference is that the latter is a buffered version of the former, so when you use the former, you’ll bypass the buffer and distort the data. And one side using aDataOutputStreamto write data would be entirely incompatible to the other side using aReaderto read the data. You should not mix them up.getInputStream()orgetOutputStream()throw an exception. Consider the entireSocketas being in an erroneous state and bail out. In case of a client, decide to try to connect again or to quit, in case of the server, wait for such a new attempt or proceed without that particular client.