Java網路編程之TCP通訊

來源:互聯網
上載者:User

標籤:

一、概述

  Socket類是Java執行用戶端TCP操作的基礎類,這個類本身使用代碼通過主機作業系統的本地TCP棧進行通訊。Socket類的方法會建立和銷毀串連,設定各種Socket選項。

  ServerSocket類是Java執行伺服器端操作的基礎類,該類運行於伺服器,監聽入站TCP串連,每個socket伺服器監聽伺服器的某個連接埠,當遠程主機的用戶端嘗試串連此連接埠時,伺服器就被喚醒,並返回一個表示兩台主機之間socket的正常Socket對象。

二、什麼是TCP?  

  TCP是一種連線導向的、可靠的、基於位元組流的傳輸層通訊協定。TCP通訊分為用戶端和伺服器端,對應的對象是分別是Socket和ServerSocket。

  當一台電腦需要與另一台遠端電腦串連時,TCP協議會讓他們建立一個串連:用於發送和接收資料的虛擬連結。TCP協議負責收集資訊包,並將其按適當的次序放好傳送,在接收端收到後再將其正確的還原。為了保證資料包在傳送中準確無誤,TCP使用了重發機制:當一個通訊實體發送一個訊息給另一個通訊實體後需要收到另一個實體的確認資訊,如果沒有收到確認資訊,則會再次重發剛才發送的資訊。

  

三、TCP通訊  1、建構函式

  Socket類實現用戶端通訊端,通過建構函式可以指定希望串連的主機和連接埠。主機可以指定為InetAddress或String,連接埠始終指定為0到65535之間的int值。

 Socket s=new Socket("127.0.0.1", 10001);//建立一個流通訊端並將其串連到指定主機上的指定連接埠號碼

   ServerSocket類實現伺服器通訊端。伺服器通訊端等待請求通過網路傳入,它基於該請求執行某些操作,然後向要求者返回結果。

 ServerSocket ss=new ServerSocket(10001);//建立綁定到特定連接埠的伺服器通訊端
   2、例子:TCP檔案複製

  用戶端:

public class ClientDemo{    public static void main(String[] args) throws UnknownHostException, IOException    {        Socket s=new Socket("127.0.0.1", 10004);                BufferedReader buf = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\1.txt"));        String line=null;                /*PrintWriter out=new PrintWriter(s.getOutputStream(),true);                while((line=buf.readLine())!=null)        {            out.println(line);        }        */                BufferedWriter out=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));        while((line=buf.readLine())!=null)        {            out.write(line);            out.newLine();            out.flush();        }        s.shutdownOutput();        BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));                String str=in.readLine();                System.out.println(str);                s.close();                buf.close();    }}

  伺服器端:

public class ServerDemo{    public static void main(String[] args) throws IOException    {        ServerSocket ss=new ServerSocket(10004);            Socket s=ss.accept();            BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));        String line=null;                /*PrintWriter buf=new PrintWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\2.txt"),true);        while((line=in.readLine())!=null)        {                buf.println(line);        }*/        BufferedWriter buf=new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\2.txt"));        while((line=in.readLine())!=null)        {                buf.write(line);            buf.newLine();            buf.flush();        }        PrintWriter out=new PrintWriter(s.getOutputStream(),true);        out.println("傳輸成功!");        ss.close();        buf.close();    }}
四、Socket在瀏覽上的應用

  我們可以在Eclipse中編寫伺服器端,然後利用瀏覽器進行訪問。

  eg、伺服器端代碼為:

public class SocketServer{    public static void main(String[] args) throws IOException     {        ServerSocket server=new ServerSocket(11000);        Socket client=server.accept();        PrintWriter out=new PrintWriter(client.getOutputStream(),true);        out.println("你好!");        server.close();    }}

  然後開啟IE瀏覽器,在地址中輸入http://192.168.1.120:11000/(192.168.1.120為本機IP地址),結果顯示為:

  

  在正常的應用中,瀏覽器是向Tomacat伺服器發出請求,以得到網頁圖片等資源。而tomca就是用Java寫的伺服器端軟體。

  現在我們編寫伺服器端為:

public class SocketServer{    public static void main(String[] args) throws IOException     {        ServerSocket server=new ServerSocket(11000);        Socket client=server.accept();        PrintWriter out=new PrintWriter(client.getOutputStream(),true);        BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));        String line=null;        while((line=in.readLine())!=null)            System.out.println(line);        out.println("你好!");        server.close();    }}

  然後在利用瀏覽器訪問,可以看到瀏覽器(用戶端)發給伺服器端的要求標頭資料為:

  

  利用上述原理,我們可以自己編寫類似IE的瀏覽器端(用戶端)軟體。首先在Tomcat的安裝目錄C:\apache-tomcat-7.0.62\webapps\myweb中添加一個demo.html資源,然後編寫用戶端,代碼如下:

public class ClientDemo{    public static void main(String[] args) throws UnknownHostException, IOException    {        Socket s=new Socket("192.168.1.120",8080);        PrintWriter out=new PrintWriter(s.getOutputStream(),true);                //將要求標頭發給伺服器        out.println("GET /myweb/demo.html HTTP/1.1");        out.println("Accept:*/*");        out.println("Host: 192.168.1.120:11000");        out.println("Connection: Keep-Alive");                //輸出空行,此步驟不可少        out.println();        BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));        String line=null;        //返回伺服器的回應檔        while((line=in.readLine())!=null)        {            System.out.println(line);        }        s.close();    }}

  接下來,啟動Tomcat。即雙擊C:\apache-tomcat-7.0.62\bin中startup.bat檔案。然後運行上述用戶端代碼,此時可以看到Tomacat返回的響應資料:

  

  

  

Java網路編程之TCP通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.