2016-04-28 1 views
0

インターネット上のハロープログラマー。私は現在、オペレーティングシステムの本を踏んでいますが、次のコードを含むいくつかの演習があります。サーバーとクライアントのやりとり

これは、サーバーのコード

import java.net.*; 
import java.io.*; 
public class DateServer{ 

    public static void main(String[] args) { 
     try { 
       ServerSocket sock = new ServerSocket(6013); 
       // now listen for connections 
       while (true) { 
      Socket client = sock.accept(); 
      PrintWriter pout = new 
      PrintWriter(client.getOutputStream(), true); 
      // write the Date to the socket 
      pout.println(new java.util.Date().toString()); 
      // close the socket and resume 
      // listening for connections 
      client.close(); 
      } 
     } 
     catch (IOException ioe) { 
      System.err.println(ioe); 
     } 
    } 
} 

あるサーバーは、ソケットを作成し、それに日付値を書き込んでいる私の理解するので、これは、クライアントコード

import java.net.*; 
import java.io.*; 
public class DateClient{ 

    public static void main(String[] args) { 
     try { 
       //make connection to server socket 
       Socket sock = new Socket("127.0.0.1",6013); 
       InputStream in = sock.getInputStream(); 
       BufferedReader bin = new 
       BufferedReader(new InputStreamReader(in)); 
       // read the date from the socket 
       String line; 
       while ((line = bin.readLine()) != null) 
        System.out.println(line); 
       // close the socket connection 
       sock.close(); 
      } 
     catch (IOException ioe) { 
      System.err.println(ioe); 
     } 
    } 
} 

です。クライアントはその後、サーバに接続し、そのソケットに値を書き出すことに時間がかかります。私はこのコードを正しく解釈していますか?これはソケットでの私の最初の経験です。

今実際の質問です。私はクライアントがサーバーに接続して(そしてあなたが接続されているというメッセージを表示して)、サーバーが処理できるようにサーバーに値を送ることができるようにします。これをどうやってやりますか?私はDataOutputStreamとDataInputStreamを試してみましたが、これまでに使ったことはありません。どんな助けでも大いに感謝します。

+2

このサイトには多くの例を:クライアントがどのように見えるはずです

ServerSocket sock = new ServerSocket(6013); // now listen for connections while (true) { Socket client = sock.accept(); InputStream in = client.getInputStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); // read the date from the client socket String line; while ((line = bin.readLine()) != null) System.out.println(line); // close the socket connection client.close(); } 

サーバーは次のようになります。特にチャットクライアントに関する最近の質問の弾幕を見てください。 – KevinO

答えて

0

あなたは正しいですか?サーバーはソケットに書き込み、クライアントはソケットから読み取ります。あなたはそれを逆転したい。

try 
{ 
    // make connection to server socket 
    Socket sock = new Socket("127.0.0.1", 6013); 
    PrintWriter out = new PrintWriter(sock.getOutputStream(), true); 

    // send a date to the server 
    out.println("1985"); 
    sock.close(); 
} 
catch (IOException ioe) 
{ 
    System.err.println(ioe); 
} 
+0

それは私が正しく理解していたことを安心させてくれてありがとう!サーバーを実行した後、クライアントが何も標準出力に出力していないように見えます。私はデバッグして、なぜそれがわかるか分かります。 – Xuluu

+0

hmmm理由はわかりませんが、コードがwhileステートメントを打つことは決してないようです。クライアントを実行すると、実行され、プリントステートメントなしでソケットが閉じられます。 – Xuluu

+0

例で示したコードでは、コンソールに出力するサーバーでなければなりません。 –

関連する問題