JAVA UDP发送和接收 代码

UDPSend.java

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


public class UDPSend {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		try {
			String host = "127.0.0.1";
			int port = 8888;
			String msg = "send data.";
			InetAddress address = InetAddress.getByName(host);
			
			DatagramPacket packet = new DatagramPacket(msg.getBytes(), 
					msg.length(), address, port);
			DatagramSocket dsocket = new DatagramSocket();
			dsocket.send(packet);
			dsocket.close();
			
		}catch (Exception e) {
			
		}
	}
	
	

}

 

UDPReceive.java

import java.net.DatagramPacket;
import java.net.DatagramSocket;


public class UDPReceive {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		try {
			int port = 8888;
			DatagramSocket dsocket = new DatagramSocket(port);
			byte[] buffer = new byte[2048];
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			for(;;) {
				dsocket.receive(packet);
				String msg = new String(buffer, buffer.length);
				System.out.println(packet.getAddress() + ":" + msg);
				
			}
			
		}catch (Exception e) {
			
		}
	}

}

 

你可能感兴趣的:(JAVA)