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培训、期待与您交流! ----------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值