2012-03-03 2 views
1

私はクライアント側とサーバー側のプログラムを入手しました。クライアントは、文字列を送信することによってサーバーと話し、その後、文字列を大文字に変換して返信します。問題は、クライアントがサーバーから文字列を受け取らないことです。サーバーだけが文字列で2を出力し、サーバーはIOExceptionをスローします。私はクライアントが接続を閉じたのでそれを推測する。しかし、なぜクライアントはサーバーからメッセージを受け取らないのですか?どのようにこの問題を克服する? おかげクライアントとサーバー間の通信に不具合がありました

Client: 
package solutions; 

import java.io.*; 
import java.net.*; 

class SocketExampleClient { 

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

    String host = "localhost"; // hostname of server 
    int port = 5678;   // port of server 
    Socket s = new Socket(host, port); 
    DataOutputStream dos = new DataOutputStream(s.getOutputStream()); 
    DataInputStream dis = new DataInputStream(s.getInputStream()); 

    dos.writeUTF("Hello World!"); 
    System.out.println(dis.readUTF()); 

    dos.writeUTF("Happy new year!"); 
    System.out.println(dis.readUTF()); 

    dos.writeUTF("What's the problem?!"); 
    System.out.println(dis.readUTF()); 

    } 
} 

サーバー:

package solutions; 

import java.io.*; 
import java.net.*; 

class SocketExampleServer { 

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

    int port = 5678; 
    ServerSocket ss = new ServerSocket(port); 
    System.out.println("Waiting incoming connection..."); 

    Socket s = ss.accept(); 
    DataInputStream dis = new DataInputStream(s.getInputStream()); 
    DataOutputStream dos = new DataOutputStream(s.getOutputStream()); 

    String x = null; 

    try { 
     while ((x = dis.readUTF()) != null) { 

     System.out.println(x); 

     dos.writeUTF(x.toUpperCase()); 
     } 
    } 
    catch(IOException e) { 
     System.err.println("Client closed its connection."); 
    } 
    } 
} 

出力:あなたのクライアントのコードでは、サーバーの入力を待つん

Waiting incoming connection... 
Hello World! 
Happy new year! 
What's the problem?! 
Client closed its connection. 

答えて

2

あなたのメインプログラムが終了しているために別々のスレッドを実行する必要があります。次のコードを追加すると正常に動作します。 :) UPDATE-私はちょうどあなたのコードが自分のコンピュータ上で正常に動作していることを理解しました。そして、予想通りに文字列を出力します。 DataInputStream.readUTF()が正しくブロックされ、応答を受け取りました。あなたはまだ問題を抱えていますか?

Thread t = new Thread(){ 
public void run() 
{ 
    for(;;) 
    { 
     String s = null; 
    try 
     { 
     s = dis.readUTF(); 
    } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
     } 
     while(s!=null) 
     { 
      System.out.println("Output: " + s); 
     try 
     { 
     s = dis.readUTF(); 
    } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
    } 
    }}}}; 
    t.start(); 
+0

しかし、なぜサーバーからの応答を読み込む前に終了しますか?クライアントは次に書き込みを行い、次に書き込みなどを行います。 – uml

+0

大文字で書かれたサーバからの応答を表示します。クライアント側から渡されたサーバ側の文字列は画面に表示されません。 – uml

0

?あなたのクライアントが終了したメッセージの送信を終了し、ソケットが閉じられたときにabviosuly。

あなたは、サーバーの答えを聞いたり、それがサーバからの応答を読む機会を持って前にlook at this example

+0

クライアントは、サーバーから文字列を読み取るはずの次の行を文字列で一度送信します。 – uml

+0

ああ、申し訳ありませんが、私はこれをこのように見たことはありません。チェックするだけで何かをやろうとしたことを理解しましたが、上記の例で説明したアプローチを実際に使用する必要があります。 – giorashc

関連する問題