Java网络通信之UDP通信

目录

网络编程

网络通信要素

UDP通信


网络编程

网络参考模型有两个:OSI参考模型和TCP/IP参考模型

 

网络通信要素

IP地址:InetAddress

  • 网络中设备的标识
  • 不易记忆,可用主机名
  • 本地回环地址:127.0.0.1 主机名:localhost
  • Java中的InetAddress是一个代表IP地址的对象。IP地址可以由字节数组和字符串来分别表示,InetAddress将IP地址以对象的形式进行封装,可以更方便的操作和获取其属性。InetAddress没有构造方法,可以通过两个静态方法获得它的对象。

端口号:

  • 用于标识进程的逻辑地址,不同进程的标识
  • 有效端口:0~65535,其中0~1024系统使用或保留端口

传输协议:

  • 通讯的规则
  • 常见协议:TCP,UDP

UDP通信

UDP通信的特点:

  • 将数据源和目的封装成数据包中,不需要建立连接(面向无连接);
  • 每个数据报的大小在限制在64k内;
  • 因无连接,是不可靠协议;
  • 不需要建立连接,速度快

Socket 

网络通信其实就是Socket间的通信;

Socket就是为网络服务提供的一种机制;

通信的两端都有Socket;

数据在两个Socket间通过IO传输

 UDP传输的过程:

发送端与接收端是两个独立的运行程序

发送端:

在发送端,要在数据包对象中明确目的地IP及端口。

DatagramSocket ds = new DatagramSocket();  //创建udp服务,建立DatagramSocket对象
//确定发送的数据,并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress address, int port) 
byte[] by = “hello,udp”.getBytes();
DatagramPacket dp = new DatagramPacket(by,0,by.length,InetAddress.getByName(“127.0.0.1”),10000);
//通过socket服务,将已有的数据包发送出去。通过send方法
ds.send(dp);
//关闭资源
ds.close();

接收端:

在接收端,要指定监听的端口。

/*定义udpsocket服务。通常会监听一个端口。
其实就是给这个接收网络应用程序定义数字标识。
方便于明确哪些数据过来该应用程序可以处理。
*/
DatagramSocket ds = new DatagramSocket(10000);  //10000为指定的端口号
//定义一个数据包,因为要存储接收到的字节数据,
//因为数据包对象中有更多功能可以提取字节数据中的不同数据信息
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by,by.length);
//通过服务的receive方法将收到数据存入数据包中
ds.receive(dp); //阻塞式方法
String str = new String(dp.getData(),0,dp.getLength());
System.out.println(str+"--"+dp.getAddress());
//关闭资源
ds.close();

例1:通过udp传输方式,将一段文字数据发送出去。

class  UdpDemo {
  public static void main(String[] args) throws Exception
  {
    DatagramSocket ds=new DatagramSocket(8888);
    byte[] buf="hello world".getBytes();  //将字符串转成字节数组
    DatagramPacket dp=new DatagramPacket(buf,buf.length, InetAddress.getByName("192.168.1.254"),10000);
    ds.send(dp);
    ds.close();
  }
}

 

 

 

例2:定义一个应用程序,用于接收udp协议传输的数据并处理。

public class Demo {
  public static void main(String[] args) throws Exception
  {
   //创建udp socket,建立端点
    DatagramSocket ds=new DatagramSocket(10000);
    while(true)
    {
      //定义数据包。用于存储数据
      byte[] buf=new byte[1024];
      DatagramPacket dp=new DatagramPacket(buf,buf.length);
    //通过服务的receive方法将收到数据存入数据包中
      ds.receive(dp);
    //通过数据包的方法获取其中的数据
      String ip = dp.getAddress().getHostAddress();
      String data = new String(dp.getData(),0,dp.getLength());
      int port = dp.getPort();
      System.out.println(ip+"::"+data+"::"+port);
    }
  }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值