如何通过UDP协议实现信息的通信?

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

import org.junit.Test;

/*DatagramSocket:发送和接受 
 *DatagramPacket:一个容器,把数据封装起来
 * 
 * UDP的编程
 * */
public class TestUDP {
   //发送端
	@Test
	public void send(){
		//1.DatagramSocket的对象
		DatagramSocket ds=null;
		try {
			ds = new DatagramSocket();
			byte[] b="大家好,今天天气很好".getBytes();
			//2.DatagramPacket:一个容器,把数据封装起来
			DatagramPacket pack=new DatagramPacket(b,0,b.length,InetAddress.getByName("127.0.0.1"),9090);
			//3.发送数据
			ds.send(pack);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(ds!=null){
				ds.close();
			}
		}
		
		
		
	}
	//接受端
	@Test
	public void rceive(){
		
		DatagramSocket ds=null;
		try {
			ds = new DatagramSocket(9090);
			byte[] b=new byte[1024];
			DatagramPacket pack=new DatagramPacket(b,0,b.length);
			//接受数据
			ds.receive(pack);
			
			String str=new String(pack.getData(), 0, pack.getLength());
			System.out.println(str);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(ds!=null){
				ds.close();
			}
		}
		
		
		
	}
}

 

你可能感兴趣的:(JAVA)