2016-04-28 187 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); 
     } 
    } 
} 

所以我的理解服務器創建套接字,並寫日期值給它。然後客戶端變長並連接到服務器並寫出該套接字中的值。我是否正確解釋此代碼?這是我第一次使用socket。

現在爲我的實際問題。我想讓客戶端連接到服務器(並打印出一條表示您已連接的消息),然後能夠將值發送到服務器,以便服務器可以處理它。我會如何去做這件事?我已經試過修改DataOutputStream和DataInputStream,但我從來沒有使用過。任何幫助將不勝感激。

+2

本網站上這樣的例子很多。特別關注最近關於聊天客戶端的問題。 – KevinO

回答

0

你是對的。您將服務器寫入套接字並從套接字讀取客戶端。你想扭轉這一點。

服務器應該是這樣的:

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(); 
} 

客戶端應該是這樣的:

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

嗯我不知道爲什麼,但它似乎代碼是從來沒有擊中while語句。當我運行客戶端時,它執行並關閉套接字而沒有任何打印語句。 – Xuluu

+0

用示例中的代碼,它應該是打印到控制檯的服務器。 –