JavaSE学习笔记--网络编程之UDP

来源:互联网 发布:淘宝亏本冲量 编辑:程序博客网 时间:2024/04/29 16:22
 package com.itcast.NWPr;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress; /**  * UDP:面向无连接,不可靠,速度快。相当于步话机。  * TCP:面向连接,可靠,速度相对慢。相当于打电话。  * 需求:UDP演示  * udp发送端的思路:  * 1,建立udp的socket服务。   * 2,将要发送的数据封装成数据包。  * 3,通过udp的socket服务,将数据包发送取出。  * 4,建议关闭资源。   *  *udp的接收端:     * 思路:  * 1,使用DatagramSocket类,建立udp的socket服务。服务。并监听一个端口。  * 2,预先定义好一个字节数组作为数据包中的容器,使用这个数据包存储接收到的数据。  * 3,通过receive方法接收数据。  * 4,通过数据包对象的功能来完成对接收到的数据进行解析。  * 5,可以对资源进行关闭。  *  * @param args  * @throws Exception   */public class SendDemo { public static void main(String[] args) throws Exception{  //udp发送端的思路:  //1,建立udp的socket服务。  //要使用DatagramSocket类,此类表示用来发送和接收数据报包的套接字。  DatagramSocket ds = new DatagramSocket();  //2,将要发送的数据封装成数据包。  //要使用DatagramPacket类。  //DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.54.9"),10000);  //InetAddress,此类表示互联网协议 (IP) 地址。InetAddress.getByName("192.168.54.9")获取一个IP对象  byte[] buf = "Hello哥们来了!".getBytes();  DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),12345);  //3,通过udp的socket服务,将数据包发送取出。  ds.send(dp);  //4,建议关闭资源。   ds.close(); }}                 
package com.itcast.NWPr;
import java.net.DatagramPacket;import java.net.DatagramSocket;
public class RecieveDemo {
 /***udp的接收端:     * 思路:  * 1,使用DatagramSocket类,建立udp的socket服务。服务。并监听一个端口。  * 2,预先定义好一个字节数组作为数据包中的容器,使用这个数据包存储接收到的数据。  * 3,通过receive方法接收数据。  * 4,通过数据包对象的功能来完成对接收到的数据进行解析。  * 5,可以对资源进行关闭。  * @param args  * @throws Exception   */ public static void main(String[] args) throws Exception {  /*---接下来,看看接收端的定义---*/  //udp的接收端思路:   //1,使用DatagramSocket类,建立udp的socket服务。服务。并监听一个端口。  DatagramSocket ds = new DatagramSocket(12345);   //2,预先定义好一个字节数组作为数据包中的容器,使用这个数据包存储接收到的数据。  byte[] buf = new byte[1024];  DatagramPacket dp = new DatagramPacket(buf,buf.length);   //3,通过receive方法接收数据。  ds.receive(dp);   //4,通过数据包对象的功能来完成对接收到的数据进行解析。  String hostAddress = dp.getAddress().getHostAddress();  String hostName = dp.getAddress().getHostName();  int port = dp.getPort();  String text1 = dp.getData().toString();  String text2 = new String(dp.getData(),0,dp.getLength());    System.out.println("hostAddress="+hostAddress);  System.out.println("hostName="+hostName);  System.out.println("port="+port);  System.out.println("text1="+text1);  System.out.println("text12="+text2);     //5,可以对资源进行关闭。  ds.close(); }
}上面是我通过代码的方式对UDP的发送和接收的总结。
原创粉丝点击