Java網路編程總結下__演算法

來源:互聯網
上載者:User

              

 

     Java網路編程基礎

 TCP/UDP協議

             TCP (Transmission Control Protocol)和UDP(User Datagram Protocol)協議屬於傳輸層協議。

 

 IP協議

             IP協議(Internet Protocol)又稱互連網協議,是支援網間互連的資料報協議,它與TCP協議(傳輸控制通訊協定)一起構成了TCP/IP協議族的核心。

 

 

IP地址

 

TCP/IP用IP地址來標識源地址和目的地址

IP地址功能:為實現網路中不同電腦之間的通訊,每台機器都必須有一個與眾不同的標識---IP地址;

 

IP地址格式:數字型,32位,由4個 8位的位元組成,每8位之間用圓點隔開,如:166.111.78.98;

 

IP地址組成:網路標識 (netId) + 主機標識(hostId);

 

Java網路功能

 

Java所提供的網路功能可大致分為三大類:

URL和URLConnection

Socket

Datagram

 

URL類和URLConnection類

 

URL(Uniform Resource Locator)----統一資源定位器,表示Internet上某一資源的地址。

 

URL組成: 協議名和資源名

       protocol:resourceName

 

URL舉例:

–        http://www.sun.com/

–        http://home.netscape.com/home/welcome.html

–        http://http://www.sun.com.cn/developers/

 

建立URL類對象

 

   常用構造方法

–        public URL(String spec);

       URLu1 = new URL("http://www.cctv.com.cn/default.shtml"); public URL(URLcontext, String spec);

       URLu2 = new URL(u1, “sports.html”);

–        public URL(String protocol,String host, String file);

        URL u3 = new URL(“http”, “www.sun.com”,  “developers/index.html” );

–        public URL (String protocol,String host, int port,  String file);

       URLu4 = new URL(“http”, “www.sun.com”, 80, “developers/index.html” );

 

URL類中擷取對象特徵的方法

 

URL類中一些很基本的方法如下:

  publicfinal Obect getContent(); //這個方法取得傳輸協議。

 publicString getFile(); //這個方法取得資源的檔案名稱。

public StringgetHost(); //這個方法取得機器的名稱。

  publicint getPort(); //這個方法取得連接埠號碼。

public StringgetProtocol(); //這個方法取得傳輸協議。

public StringtoString(); //這個方法把URL轉化為字串

 

URL對象的建立及使用

 

import java.net.*;

import java.io.*;

class TestUrl

{public static void main(String args[]) {

 try{

URL url=newURL("http://www.cctv.com.cn/default.shtml");

 System.out.println("the Protocol:"+url.getProtocol());

 System.out.println("the hostname: "+url.getHost());

 System.out.println("the port:"+url.getPort());

 System.out.println("thefile:"+url.getFile());

 System.out.println(url.toString());

 }

catch(MalformedURLException e) {

 System.out.println(e);

       }

   }

}

 

擷取URL對象的內容

importjava.io.*;

importjava.net.*;

public class URLReader{

       publicstatic void main(String args[]){

              try{       URL tirc = newURL("http://www.tsinghua.edu.cn/");

                     BufferedReaderin = new BufferedReader(new

                            InputStreamReader(tirc.openStream()));

                     Strings;

                     while((s= in.readLine())!=null)

                            System.out.println(s);

                     in.close();     

              }catch(MalformedURLExceptione) {

                     System.out.println(e);

              }catch(IOExceptione){

                     System.out.println(e);

              }     

   }

}

 

URLConnection類

 

使用URLConnection對象的一般方法如下:

    (1)建立一個URL對象。

    (2)調用URL對象的openConnection()方法建立這個URL的URLConnection對象。

    (3)配置URLConnection。

    (4)讀首部欄位。

    (5)擷取輸入資料流並讀資料。

    (6)擷取輸出資料流並寫資料。

    (7)關閉串連。

 

URLConnection對象的建立及使用

 

importjava.io.*;

importjava.net.*;

import java.util.Date;

class TestUrlConnection

{public static void  main(String args[]) throws Exception

       {System.out.println("starting....");

       intc;

       URLurl=new URL("http://www.baidu.com");

       URLConnection  urlcon=url.openConnection();

       System.out.println("thedate is :"+new Date(urlcon.getDate()));

       System.out.println("content_type:"+urlcon.getContentType());

       InputStreamin=urlcon.getInputStream();

       while(((c=in.read())!=-1))

              {System.out.print((char)c);}

       in.close();

       }

}

 

InetAddress類

 

建立InetAddress對象

public staticInetAddress getLocalHost()  

public staticInetAddress getByName (String host)

public staticInetAddress[] getAllByName(String host)

 

InteAddress類方法的使用

 

importjava.net.*;

importjava.io.*;

public class TestAddress{

       publicstatic void main(String args[]){

       try{

              InetAddressinetadd;

              inetadd=InetAddress.getLocalHost();

              System.out. println("hostname="+inetadd.getHostName());

              System.out. println("hostname="+inetadd.getHostAddress());

              System.out. println(inetadd.toString() );}

       catch(Exceptione) {

              System.out.println(e);

              }

 

通訊端Socket的應用

 

兩個Java應用程式可通過一個雙向的網路通訊串連實現資料交換,這個雙向鏈路的一端稱為一個socket。

 

socket通常用來實現client-server串連。

 

java.net包中定義的兩個類Socket和ServerSocket,分別用來實現雙向串連的client和server端

 

建立串連時所需的定址資訊

–        遠端電腦的機器名或IP地址

–        試圖串連的連接埠號碼(Port number)

 

Socket編程的四個基本步驟

  建立socket; 開啟串連到socket的輸入/輸出流; 按照一定的協議對socket進行讀/寫操作; 關閉socket;

 

建立socket

 

Socket/ServerSocket類的構造方法

Socket(InetAddress  address,int  port);

Socket(InetAddress  address, int port, boolean  stream);

Socket(String  host, int port);

Socket(String  host, int port, boolean stream);

ServerSocket(int  port);

ServerSocket(int  port, int count);

 

Socket應用舉例--伺服器端

 

importjava.net.*;

importjava.io.*;

public class TestServer {

         public static void main(String args[]) {

         try {       ServerSocket s = new ServerSocket(9876);

               while (true) {

                Socket s1 = s.accept();

                OutputStream os = s1.getOutputStream();

                DataOutputStream dos = newDataOutputStream(os);

dos.writeUTF "Hello,socket is veryintersting!" + "\n bye-bye!");

                dos.close();

                s1.close(); }

           }catch (IOException e) {System.out.println("出錯:" + e);}

         }

}

 

Socket應用舉例--用戶端

 

importjava.net.*;

importjava.io.*;

public class TestClient {

         public static void main(String args[]) {

              try{

                     Sockets1 = new Socket("127.0.0.1", 9876);

                     InputStreamis = s1.getInputStream();

                     DataInputStreamdis = new DataInputStream(is);

                     System.out.println(dis.readUTF());

                     dis.close();

                     s1.close();

              }catch (ConnectException connExc) {

                     System.err.println("伺服器串連失敗。");

              }catch (IOException e) {}

         }

}

 

資料通訊端的應用

 

import java.net.*;

public class UDPScan

{public static void main(String args[])

 { for (intport=1024;port<=65535;port++) {

    try {DatagramSocketserver=new DatagramSocket(port);

         server.close(); }

  catch(SocketException e) {

    System.out.println("there is a server in port"+port+".");}

   }

 }

}

 

資料通訊端應用程式

 

importjava.net.*;

import java.io.*;

public class TestClient {

         public static void main(String args[]) {

              try{

                     Sockets1 = new Socket("127.0.0.1", 8888);

                     InputStreamis = s1.getInputStream();

                     DataInputStreamdis = new DataInputStream(is);

                     System.out.println(dis.readUTF());

                     dis.close();

                     s1.close();

              }catch (ConnectException connExc) {

                     System.err.println("伺服器串連失敗。");

              }catch (IOException e) {

              }

         }

}

    關於網路編程,基本上就是這些東西,對於網路基礎部分,在實際編程中不會用到,比較常用的是UDP和TCP協議編程以及Socket編程的部分,這是十分重的,還有就是那幾個常用的關於網路編程部分的幾個常用類,也是我們應該掌握的。

 

聯繫我們

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