使用UDP协议编写一个网络程序,设置接收端程序的监听端口是8001,发送端发送的数据是“Hello, world”。

来源:互联网 发布:软件如何授权 编辑:程序博客网 时间:2024/05/18 23:13

使用UDP协议编写一个网络程序,设置接收端程序的监听端口是8001,发送端发送的数据是“Hello,world”。

package net.com;


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 {
        // TODO Auto-generated method stub
        DatagramSocket ds = new DatagramSocket(3000);
        String str = "Hello,world";
        DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(),
                InetAddress.getByName("localhost"),8001);
        System.out.println("发送信息");
        ds.send(dp);//该方法用于发送DatagramPacket数据包,发送的数据包中包含将要
                   //发送的数据,数据长度,远程主机的IP地址和端口号
        ds.close();
    }


}


package net.com;


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


public class UDPREC{
   
public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
    byte[] buf = new byte[1024];//建立一个长度为1024的子节数组,用于接受数据
    DatagramSocket ds = new DatagramSocket(8001);//定义一个DatagramSocket的对象,监听的端口号为8001
    DatagramPacket dp = new DatagramPacket(buf, 1024);//定义一个DatagramPacket的对象,用于接收数据
    System.out.println("等待接收数据");
    ds.receive(dp);//没有数据则会阻塞
    String str = new String(dp.getData(), 0, dp.getLength()) + "from " 
    + dp.getAddress().getHostAddress() + ": " + dp.getPort();
    System.out.println(str);
    ds.close();
    }


}


阅读全文
0 0
原创粉丝点击