Java網路編程

來源:互聯網
上載者:User

標籤:

.TCP程式設計

在JAVA中使用Socket(即通訊端)完成TCP程式的開發,使用此類可以方便的建立可靠的,雙向的,持續的,點對點的通訊串連。

在Socket的程式開發中,伺服器端使用ServerSocke等待用戶端的串連,對於java的網路程式來講,每一個用戶端都使用一個Socket對象表示。

.ServerSocket類的常用方法

序號 方法 類型 描述
1 public ServerSocket(int port)throws IOException 建構函式 建立ServerSocket執行個體,並監聽指定的連接埠。
2 public Socket accept()throws IOException 普通函數 等待用戶端串連,此方法串連之前一直阻塞
3 public InetAddress getInetAddress() 普通函數 返回伺服器的IP地址
4 public boolean isClosed() 普通函數 返回ServerSocket的關閉狀態
5 public void close()throws IOException 普通函數 關閉ServerSocket

在伺服器端每次運行時都要使用accept()方法等待用戶端串連,此方法執行之後伺服器端將進入阻塞狀態,直到用戶端串連之後程式才可以向下繼續執行。此方法的傳回值類型是Socket,每一個Socket都表示一個用戶端對象。

.Socket類的常用方法:

序號 方法 類型 描述
1 public Socket(String host , int port)throws UnknownHostException,IOException 構造 構造Socket對象,同時指定要串連伺服器的主機名稱及串連連接埠號碼。
2 public InputStream getInputStream() throws IOException 普通 返回此通訊端的輸入資料流
3 public OutputStream getOutputStream() throws IOException   返回此通訊端的輸出資料流
4 public void close() throws IOException   關閉此Socket
5 public boolean isClosed()   判斷此通訊端是否被關閉

            

.第一個TCP程式--Echo程式

      Echo 程式是一個網路編程通訊互動的一個典型的案例,稱為回應程式,即用戶端輸入哪些內容,伺服器端會在這些內容前加上“ECHO:”並將資訊發回用戶端。

      之前的程式碼,伺服器端每次執行完畢後,伺服器都會退出,這是因為伺服器端只能接受一個用戶端的串連,主要是由於accept()方法只能使用一次,本程式中將通過

迴圈的方法使用accept()方法,這樣,每一個用戶端執行完畢後,伺服器端都可以重新等待使用者串連。

單線程範例:

EchoClient 
 1 public class EchoClient { 2     public static void main(String[] args) throws IOException { 3  4         Socket client = new Socket("localhost", 8888); 5         BufferedReader buf = null; 6         PrintStream out = null; 7         out = new PrintStream(client.getOutputStream()); 8         out.println(1); 9         BufferedReader input = null;10         input = new BufferedReader(new InputStreamReader(System.in));11         buf = new BufferedReader(new InputStreamReader(client.getInputStream()));12         boolean flag = true;13 14         while (flag) {15             System.out.println("Please Key In:");16             String str = input.readLine();17             out.println(str);18             if ("bye".equals(str)) {19                 flag = false;20             } else {21                 String echo = buf.readLine();22 23                 System.out.println("1111" + echo);24             }25         }26         client.close();27         buf.close();28     }29 }

單線程範例:

EchoServer 
 1 public class EchoServer { 2     public static void main(String[] args) throws IOException { 3         ServerSocket server = null; 4         Socket client = null; 5         PrintStream out = null; 6         BufferedReader buf = null; 7         server = new ServerSocket(8888); 8         boolean f = true; 9         while (f) {10             System.out.println("Server Running,Waiting for Client");11             client = server.accept();12             out = new PrintStream(client.getOutputStream());13             // 擷取用戶端輸入的資訊14             buf = new BufferedReader(new InputStreamReader(15                     client.getInputStream()));16             // 執行個體化輸出端17             out = new PrintStream(client.getOutputStream());18             boolean flag = true;19             while (flag) {20                 String str = buf.readLine();21                 if (str == null || "".equals(str)) {22                     flag = false;23                 } else {24                     if ("bye".equals(str)) {25                         flag = false;26                     } else {27                         out.println("ECHO" + str);28                     }29                 }30             }31             out.close();32             client.close();33         }34         server.close();35     }36 37 }

多線程範例:

EchoThread 
 1 public class EchoThread implements Runnable { 2  3     private Socket client = null; 4  5     public EchoThread(Socket client) { 6         this.client = client; 7     } 8  9     public void run() {10         PrintStream out = null;11         BufferedReader buf = null;12 13         try {14             buf = new BufferedReader(new InputStreamReader(15                     client.getInputStream()));16             out = new PrintStream(client.getOutputStream());17             boolean flag = true;18 19             while (flag) {20                 String str = buf.readLine();21                 if (str == null || "".equals(str)) {22                     flag = false;23                 } else {24                     if ("bye".equals(str)) {25                         flag = false;26                     } else {27                         out.println("ECHO:" + str);28                     }29                 }30             }31             out.close();32             client.close();33         } catch (Exception e) {34         }35     }36 37 }

多線程範例:

EchoServer 
 1 public class EchoServer { 2     public static void main(String[] args) throws IOException { 3         ServerSocket server = null; 4         Socket client = null; 5         PrintStream out = null; 6         BufferedReader buf = null; 7         server = new ServerSocket(8888); 8         boolean f = true; 9         while (f) {10             System.out.println("Server Running,Waiting for Client");11             client = server.accept();12             new Thread(new EchoThread(client)).start();13             14         }15         server.close();16     }17 18 }

在伺服器端,每一個串連到伺服器的用戶端Socket都會以一個線程的方式運行,這樣無論有多少個客戶串連都可以同時完成操作。

未完待續。。。

 

Java網路編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.