模拟UDP传输的发送端和接收端

本文介绍了如何创建UDP传输的发送端和接收端,包括建立Socket服务、封装与发送数据、接收与解析数据。同时,针对一次只能传输一条消息的限制,提出了优化方案,如使用BufferedReader从键盘录入内容,以及在接收端设置循环接收。最后,探讨了基于UDP创建简单聊天室的可能性。
摘要由CSDN通过智能技术生成

一、创建UDP传输的发送端

1、建立UDP的Socket服务; 
2、将要发送的数据封装到数据包中; 
3、通过UDP的Socket服务将数据包发送出去; 
4、关闭Socket服务。

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSend {
     

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

        System.out.println("发送端启动......");

        // 1、创建UDP的Socket,使用DatagramSocket对象
        DatagramSocket ds = new DatagramSocket();

        // 2、将要发送的数据封装到数据包中
        String str = "UDP传输演示:I'm coming!";

        byte[] buf = str.getBytes();  //使用DatagramPacket将数据封装到该对象的包中

        DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.191.1"), 10000);

        // 3、通过UDP的Socket服务将数据包发送出去,使用send方法
        ds.send(dp);

        // 4、关闭Socket服务
        ds.close();
    }
}
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

二、创建UDP传输的接收端

1、建立UDP的Socket服务,因为要接收数据,所以必须明确一个端口号; 
2、创建数据包,用于存储接收到的数据,方便用数据包对象的方法解析这些数据; 
3、使用UDP的Socket服务的receive方法接收数据并存储到数据包中; 
4、通过数据包的方法解析这些数据; 
5、关闭Socket服务。

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceive {
     
    public static void main(String[] args) throws IOException {

        System.out.println("接收端启动......");

        // 1、建立UDP的Socket服务
        DatagramSocket ds = new DatagramSocket(10000);

        // 2、创建数据包
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf, buf.length);

        // 3、使用接收方法将数据存储到数据包中
        ds.receive(dp);  // 该方法为阻塞式的方法

        // 4、通过数据包对象的方法解析这些数据,例如:地址、端口、数据内容等
        String ip = dp.getAddress().getHostAddress();
        int port = dp.getPort();
        String text = new String(dp.getData(), 0, dp.getLength());

        Syst
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值