您的位置:首页 > 理论基础 > 计算机网络

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

2017-12-14 18:01 876 查看
使用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();

    }

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐