Java網路編程之TCP通訊

來源:互聯網
上載者:User

標籤:通訊端   dwr   track   位元組   dmi   bin   網路編程   public   inpu   

一、概述

  Socket類是Java運行clientTCP操作的基礎類,這個類本身使用代碼通過主機作業系統的本地TCP棧進行通訊。

Socket類的方法會建立和銷毀串連,設定各種Socket選項。

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

二、什麼是TCP?  

  TCP是一種連線導向的、可靠的、基於位元組流的傳輸層通訊協定。

TCP通訊分為client和server端,相應的對象是各自是Socket和ServerSocket。

  當一台電腦須要與還有一台遠端電腦串連時,TCP協議會讓他們建立一個串連:用於發送和接收資料的虛擬連結。

TCP協議負責收集資訊包。並將其按適當的次序放好傳送。在接收端收到後再將其正確的還原。

為了保證資料包在傳送中準確無誤,TCP使用了重發機制:當一個通訊實體發送一個訊息給還有一個通訊實體後須要收到還有一個實體的確認資訊。假設沒有收到確認資訊,則會再次重發剛才發送的資訊。

  

三、TCP通訊  1、建構函式

  Socket類實現client通訊端,通過建構函式能夠指定希望串連的主機和port。

主機能夠指定為InetAddress或String,port始終指定為0到65535之間的int值。

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

   ServerSocket類實現server通訊端。

server通訊端等待請求通過網路傳入。它基於該請求運行某些操作。然後向要求者返回結果。

 ServerSocket ss=new ServerSocket(10001);//建立綁定到特定port的server通訊端

   2、範例:TCP檔案複製

  client:

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

  server端:

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中編寫server端。然後利用瀏覽器進行訪問。

  eg、server端代碼為:

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地址)。結果顯示為:

  

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

  如今我們編寫server端為:

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

  然後在利用瀏覽器訪問。能夠看到瀏覽器(client)發給server端的要求標頭資料為:

  

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

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);                //將要求標頭發給server        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;        //返回server的回應檔        while((line=in.readLine())!=null)        {            System.out.println(line);        }        s.close();    }}

  接下來,啟動Tomcat。即雙擊C:\apache-tomcat-7.0.62\bin中startup.bat檔案。然後執行上述client代碼,此時能夠看到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.