2012-01-31 49 views
0

私はクライアント - サーバーシナリオを使用しています。クライアントは、url接続を使用してサーバー(サーブレット)と通信します。ここで私が使用しているコードです。私が間違っているつもりですURLオブジェクトのストリームを使用する

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

URL url = new URL("http://localhost:8080/hello"); 
    URLConnection connection = url.openConnection(); 
    connection.setDoOutput(true); 
    ObjectOutputStream out=new ObjectOutputStream(connection.getOutputStream());//1st out put stream 
    out.writeObject(pk); 
    out.flush(); 
    out.close(); 

    ObjectInputStream in = new ObjectInputStream(connection.getInputStream());//1st instream 
    PublicKey spk=(PublicKey)in.readObject(); 
    in.close(); 

    ObjectOutputStream out1=new ObjectOutputStream(connection.getOutputStream());//2nd out put stream 
    out1.writeObject(str1); 
    out1.flush(); 
    out1.close(); 

    ObjectInputStream in1 = new ObjectInputStream(connection.getInputStream());  
    String rstr3=(String)in1.readObject(); 
    //processing 
    in1.close(); 

しかし、私はと呼ばれる例外を取得していますか?

答えて

0

URLConnectionのインスタンスは再利用できません。リソースへの接続ごとに異なるインスタンスを使用する必要があります。次のコードは正常に動作します(新しいurlconnectionオブジェクトを開きます)

URLConnection connection1 = url.openConnection(); 
ObjectOutputStream out1=new ObjectOutputStream(connection1.getOutputStream());//2nd out put stream 
    out1.writeObject(str1); 
    out1.flush(); 
    out1.close(); 

    ObjectInputStream in1 = new ObjectInputStream(connection1.getInputStream());  
    String rstr3=(String)in1.readObject(); 
    //processing 
    in1.close(); 
+0

もっとクリーンで実用的な代替手段は何ですか?毎回これをするのではなく、ちょっとだけ短いことがありますか? – Trup

+0

@Trup:私はそれを試していないが、私はあなたがconection.disconnect()を呼び出した後に再び接続オブジェクトを使用できると思います。可能であれば、私に知らせてください。 – Ashwin

関連する問題