用DatagramSocket发送数据和接收数据

接收端要先运行

package Intnet;

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

public class UdpSenddemo {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("发送端启动");
		DatagramSocket ds = new DatagramSocket();
		String s = "udp,哥们来了,接稳";
		byte buf[] = s.getBytes();
		DatagramPacket dp = 
				new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.2.143"),11603);
		ds.send(dp);
		ds.close();
		System.out.println("发送成功");
	}

}


package Intnet;

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

public class UdpRecdemo {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("接收端启动");
		DatagramSocket ds = new DatagramSocket(11603);
		byte buf[] = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buf, buf.length);
		ds.receive(dp);
		
		String ip = dp.getAddress().getHostAddress();
		int port = dp.getPort();
		String data = new String(dp.getData(),0,dp.getLength());
		//System.out.println(11);
		System.out.println(ip + "::" + port + ":" + data);
		ds.close();
	}

}

  

 

posted @ 2019-11-23 16:30  WINDZLY  阅读(872)  评论(0编辑  收藏  举报