java網絡及相關編程(黑馬程序員)

------- android培訓、java培訓、期待與您交流! ----------

首先在這篇文章中,我介紹java網絡編程,java在連接層有相關的對象!也就是說這是在網絡編程的傳輸層!

1.那麼網絡通信最重要的就是有一個身份!ip那麼java封裝了一個類InetAddress,這是一個靜態類!那麼方法可以直接用

	public static void netDemo_1() throws Exception
	{
		InetAddress inet = InetAddress.getLocalHost();//獲得主機地址ip
		inet = InetAddress.getByName("www.baidu.com");//由網絡名稱獲取ip
		System.out.println(inet);
		String addstr = inet.getHostAddress();//由以獲取的對象獲得String的地址!
		String namestr = inet.getHostName();//由以獲取的對象獲得String的名稱!
		System.out.println(addstr+"----"+namestr);
		//獲得整組的ip,由於大型網站可能有幾個ip
		InetAddress[] inets = InetAddress.getAllByName("www.baidu.com");
		for(InetAddress it:inets)
		System.out.println(it);
	}

在這段的demo中要注意一個Inetaddress對象inet是一個類,裏面封裝了ip的相關信息,inet可以通過網絡的名稱獲取,或者通過ip地址都是可以的!當你取到inet'對象時你就可以通過getHostAddress和getHostName來獲得String形式的地址值或名稱!要注意inet可能是一個數組,是由於大型網站的ip可能有好幾個地址!

2.UDP和TCP的連接是傳輸層的,也就是說必須一步一步執行!

首先看UDP對象的使用:

/*udp的傳輸主要是無連接的,那麼是不管兩端是否連接了
	 * 1.應該先建立DatagramSocket端。那麼這樣就建立了一個連接對象,直到整個程序的週期結束
	 * 2.傳遞時傳遞的是DatagramPacket對象,一個包對象!所以在建立這個對象。
	 * 3.用socket對象傳輸packet包
	 * */
	public static void netDemo_2() throws Exception 
	{
		DatagramSocket udpSocket = new DatagramSocket();
		byte[] buff = "upd frist demo".getBytes();
		DatagramPacket udpPacket = new DatagramPacket(buff,buff.length,InetAddress.getLocalHost(),10000);
		udpSocket.send(udpPacket);
		udpSocket.close();
	}

可以看出在這段代碼中由於UDP是無連接的,所以只要建立一個DtatgramSocket對象就可以了,要記住網絡編程主要是Socket'的編程!在傳輸的時候主要傳的是DatagramPacket對象,最關鍵的一句話是udpSocket.send(udpPacket);這樣就把包裝在了流對象中發了出去!

下面看接收端:

	/*1.建立接受端依舊爲Socket
	 * 2.接受對象依舊爲packet
	 * 3.用Socket接受Packet包!
	 */
	public static void netDemo_3() throws Exception
	{
		DatagramSocket udpSocket = new DatagramSocket(10000);
		byte[] buff = new byte[20];
		DatagramPacket udpPacket = new DatagramPacket(buff,buff.length);
		udpSocket.receive(udpPacket);
		System.out.println(new String(udpPacket.getData(),0,udpPacket.getLength()));
		udpSocket.close();
	}

要注意的一點就是端口的設置,在傳輸時的端口和接受的端口必須一致!否則會造成包的丟失!接受關鍵的可就是udpSocket.receive(udpPacket);這樣的一句話會把udpPacket對象接收到,再利用方法就可獲得相應的數據了!

2Tcp連接:

我給出來了tcp的代碼之所以tcp不同在tcp是一直保持連接狀態的,所以你可以斷開連接,也就是說tcp跟加可靠;

主要是建立ServerSocket‘爲服務端的東西,所以在客戶端和服務端在開啓一個Socket就可以了!

在連接的時候 ,發送data的時候要注意shutDown方法的使用,不然會出現阻塞!

class  MyServer {

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

	      ServerSocket serverSocket = null;
	      PrintWriter out = null;
	      BufferedReader in = null;
	      
	      try {
	          serverSocket =newServerSocket(1111);
	      } catch (IOException e) {
	          System.err.println("Could notlisten on port: 1111.");
	      }

	      Socket incom = null;
	      while (true) {
	          incom = serverSocket.accept();
	          out =newPrintWriter(incom.getOutputStream(),true);
	          //將字節流放入字符流緩衝之中
	          in =newBufferedReader(newInputStreamReader(
	                 incom.getInputStream()));	     
	          out.println("Hello! . .. ");
	          out.flush();
       
	          while (true) {//只有當有用戶輸入數據的時候才返回 
	            String str = in.readLine();
	             if (str ==null) {//當用戶連接斷掉時會返回空值null	               
	                 break;
	             }else {               
	                 out.println(str);
	                 out.flush();	               
	                 if (str.trim().equalsIgnoreCase("over"))
	                    break;
	             }
	          }
	          //收尾工作
	          out.close();
	          in.close();
	          incom.close();
	          serverSocket.close();
	      }
	   }
	}
	publicclass MyClient
	{
	publicstatic void main(String[] args) throws IOException
	   {    
       Socket echoSocket = null;
	    PrintWriterout = null;
	      BufferedReader in = null;
		try
	       {
			echoSocket= new Socket ( "localhost", 1111);
			out= new PrintWriter(echoSocket.getOutputStream(), true);
	        in= new BufferedReader(
	               newInputStreamReader(echoSocket.getInputStream()));
	       	}
	catch(UnknownHostException e)
	      {
			System.err.println("Don'tknow about host: localhost.");
	       }
	             System.out.println(in.readLine());
	             System.out.println(in.readLine());
	             BufferedReaderstdIn = newBufferedReader(newInputStreamReader(System.in));																
	             String userInput;
	             while ((userInput =stdIn.readLine()) != null)
	             {
	                    out.println(userInput);
	                    System.out.println(in.readLine());
	             }
	             out.close();
	             in.close();
	             echoSocket.close();
	   }
}


------- android培訓、java培訓、期待與您交流! ----------

發佈了27 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章