请你谈谈JAVA中UDP 接受与发送数据的初步步骤

1JAVA中UDP 接受与发送数据的步骤?

发送步骤:

1使用 DatagramSocket(int port) 建立socket(套间字)服务。
2将数据打包到DatagramPacket中去
3通过socket服务发送 (send()方法)
4关闭资源

import java.io.IOException;
import java.net.*;
 
public class Send {
 
	public static void main(String[] args)  {
		
		DatagramSocket ds = null;  //建立套间字udpsocket服务
		
		try {
		  ds = new DatagramSocket(8999);  //实例化套间字,指定自己的port
		} catch (SocketException e) {
			System.out.println("Cannot open port!");
			System.exit(1);	
		}
		
		byte[] buf= "Hello, I am sender!".getBytes();  //数据
		InetAddress destination = null ;
		try {
			destination = InetAddress.getByName("192.168.1.5");  //需要发送的地址
		} catch (UnknownHostException e) {
			System.out.println("Cannot open findhost!");
			System.exit(1);	
		}
		DatagramPacket dp = 
				new DatagramPacket(buf, buf.length, destination , 10000);  
		//打包到DatagramPacket类型中(DatagramSocket的send()方法接受此类,注意10000是接受地址的端口,不同于自己的端口!)
		
		try {
			ds.send(dp);  //发送数据
		} catch (IOException e) {
		}
		ds.close();
	}
}

接收步骤:

1使用 DatagramSocket(int port) 建立socket(套间字)服务,port指定监视接受端口。
2定义一个数据包(DatagramPacket),储存接收到的数据,使用其中的方法提取传送的内容。
3通过DatagramSocket 的receive方法将接受到的数据存入上面定义的包中
4使用DatagramPacket的方法,提取数据。
5关闭资源。

import java.net.*;
 
public class Rec {
 
	public static void main(String[] args) throws Exception {
		
		DatagramSocket ds = new DatagramSocket(10000);  //定义服务,监视端口上面的发送端口,注意不是send本身端口
		
		byte[] buf = new byte[1024];//接受内容的大小,注意不要溢出
		
		DatagramPacket dp = new DatagramPacket(buf,0,buf.length);//定义一个接收的包
		
		ds.receive(dp);//将接受内容封装到包中
		
		String data = new String(dp.getData(), 0, dp.getLength());//利用getData()方法取出内容
		
		System.out.println(data);//打印内容
		
		ds.close();//关闭资源	
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值