java udp简单例子

 


package com.justsee.tcpip; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UdpRecv { //先启动这个类,等待接受信息。 public static void main(String[] args) throws IOException { System.out.println("等待接受"); DatagramSocket datagramSocket = new DatagramSocket(8080);//指定接受信息的端口 byte[] buf = new byte[1024];//指定最大接受信息的大小 DatagramPacket datagramPacket = new DatagramPacket(buf, 1024); datagramSocket.receive(datagramPacket);//阻塞等待 String string = new String(datagramPacket.getData(), 0, datagramPacket.getLength()) + " from " + datagramPacket.getAddress().getHostAddress() + ":" + datagramPacket.getPort(); System.out.println(string); datagramSocket.close(); } }
 

package com.justsee.tcpip;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UdpSend {
	//后启动发送类。
	public static void main(String[] args) throws IOException {
		System.out.println("发送");
		DatagramSocket datagramSocket = new DatagramSocket();
		String str = "我是中国人!";
		//因为是发送的中文,所以str.length()改为str.getBytes().length。
		//指定发送到的ip和端口
		DatagramPacket datagramPacket = new DatagramPacket(str.getBytes(),
				str.getBytes().length, InetAddress.getByName("172.30.31.53"),
				8080);
		datagramSocket.send(datagramPacket);
		datagramSocket.close();
	}

}
/*发送和接受都是以DatagramSocket为信息载体*/
 

 

你可能感兴趣的:(.net,Java)