1

I am doing client server communication. I got both connected via URLConnection classes.

Now I am trying to send log in information to server, Server will check if information is correct else it will ask me to log in again and for this scenario lets assume log in was unsuccessful. But after getting response from server when I try again to send log in information I am getting

java.net.ProtocolException: Cannot write output after reading input.

Here is my code:

URL url = new URL(uniRL);

java.net.URLConnection connection = url.openConnection();
connection.setAllowUserInteraction(true);
connection.setDoOutput(true);

while(true){
    System.out.println("Enter 1-login , 2-Exit");
useroption = input.nextLine();
numOption = Integer.parseInt(useroption);
if( numOption == 1){
    OutputStreamWriter writer = new OutputStreamWriter(
            connection.getOutputStream());
    user_login = login();
    writer.write(user_login[0]+"@");
    writer.write(user_login[1]);
    writer.flush();
    //out.close();
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
                    connection.getInputStream()));
    while ((tempString = in.readLine()) != null) {
        decodedString = tempString;
        //System.out.println(decodedString);
        //System.out.println(decodedString.equalsIgnoreCase("unknown user"));
    }
    in.close();
    if((decodedString.equalsIgnoreCase("unknown user"))){continue;}
    else{break;}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Haseeb Wali
  • 1,181
  • 3
  • 14
  • 34
  • Which is the line where you are getting this exception ? Posting the exception trace would help. – Santosh Sep 19 '12 at 10:30
  • I am getting exception when the loop goes for its second iteration. and tries to write something for second time. – Haseeb Wali Sep 20 '12 at 05:50

1 Answers1

0

When you call in.close(), you're actually closing the stream used by the URL connection. You'd need to call url.openConnection() again to re-open the stream...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366