2016-08-31 14 views
0

Java Network Programmingを学習しようとしていますが、いくつかのロードブロッキングが発生しています。私はサーバーとクライアントをすでに作成していますが、それらを接続しようとするたびに、すぐに接続がクローズされるというエラーが表示されます。その後、私はそれを編集しようとしましたが、接続が拒否されました。これを機に、私は非常に単純なサーバー上でソケットとServerSocketsの基本をテストすることにしました。そう、私はこの2つのクラスを作ってみた:Java SocketServerはSocketクライアントからの入力を受け付けていますが、SocketクライアントはSocketServerからの入力を受け付けていません

import java.net.InetAddress; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.io.*; 

public class SimpleServer { 
    public static void main(String[] args) throws Exception { 
     System.out.println("hey there"); 
     ServerSocket server = new ServerSocket(50010); 
     Socket socket = server.accept(); 
     System.out.println("Connection at " + socket); 

     InputStream in = socket.getInputStream(); 
     int c = 0; 
     while ((c = in.read()) != -1) { 
      System.out.print((char)c); 
     } 


     OutputStream out = socket.getOutputStream(); 
     for (byte b : (new String("Thanks for connecting!")).getBytes()) { 
      out.write(b); 
      out.flush(); 
     } 

     in.close(); 
     out.close(); 
     socket.close(); 
     server.close(); 
    } 
} 

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

public class SimpleClient { 
    public static void main(String[] args) throws Exception { 
     System.out.println("Attempting connection"); 
     Socket s = new Socket("130.49.89.208", 50010); 
     System.out.println("Cool"); 

     OutputStream out = s.getOutputStream(); 
     for (byte b : (new String("Hey server\r\nThis message is from the client\r\nEnd of message\r\n")).getBytes()) { 
      out.write(b); 
      out.flush(); 
     } 

     InputStream in = s.getInputStream(); 
     int c = 0; 
     System.out.println("this message will print"); 
     while ((c = in.read()) != -1) { 
      System.out.print((char)c); 
      System.out.println("this does not print"); 
     } 

     out.close(); 
     in.close(); 
     s.close(); 
    } 
} 

サーバは、クライアントのメッセージが完全に罰金受けるが、それは、サーバーのターンのとき、クライアントへの書き込みにすべてがブロックされます。

Serverの出力:

-java SimpleServer 
----hey there 
----Connection at Socket[addr=/130.49.89.208,port=59136,localport=50010] 
----Hey server 
----This message is from the client 
----End of message 

クライアントの出力:

-java SimpleClient 
----Attempting connection 
----Cool 
----this message will print 

クライアントとサーバーの両方ことができます場合は、大学のインターネット接続とイーサネット接続に私のラップトップ上で実行します。 Javadocによる

答えて

1

は、InputStream.read()は以下のように記述されるストリームの終わりに達したために何バイトが利用可能でない場合

、値-1が返されます。このメソッドブロック入力データが利用可能な場合、ストリームの終わりが検出された場合、または例外がスローされた場合

あなたのケースでは、whileループを中断する唯一の可能性は、クライアントが接続を閉じて、ストリームの終わりが生じることです。

これは、コード化されたものとして期待されます。

0

お使いのサーバーのコードは、ここで立ち往生となっているので、決してクライアント

while ((c = in.read()) != -1) { 
     System.out.print((char)c); 
    } 
に戻って書き込みを行っていません
関連する問題