位置:首頁 > Java技術 > java實例教學 > Java套接字到單一的客戶端

Java套接字到單一的客戶端

如何使顯示信息給一個客戶機的套接字?

解決方法

下麵的示例演示如何使用Socket類的ssock.accept()方法顯示信息給一個客戶端套接字。

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BeerServer {
   public static void main(String args[]) 
   throws Exception {
      ServerSocket ssock = new ServerSocket(1234);
      System.out.println("Listening");
      Socket sock = ssock.accept();
      ssock.close(); 
      PrintStream ps = new PrintStream
      (sock.getOutputStream());
      for (int i = 10; i >= 0; i--) {
         ps.println(i + 
         " from Java Source and Support.");
      }
      ps.close();
      sock.close();
   }
}

結果

上麵的代碼示例將產生以下結果。

Listening
10 from Java Source and Support
9 from Java Source and Support
8 from Java Source and Support
7 from Java Source and Support
6 from Java Source and Support
5 from Java Source and Support
4 from Java Source and Support
3 from Java Source and Support
2 from Java Source and Support
1 from Java Source and Support
0 from Java Source and Support