java UDP通信

接收端程序:

package hzy;
import java.io.IOException;  
import java.net.DatagramPacket;  
import java.net.DatagramSocket;  
import java.net.InetAddress;  
import java.net.SocketAddress;  
import java.net.UnknownHostException;  
  
/** 
 * 接收端端程序 
 * @author ccna_zhang 
 * 
 */  
public class UDPRecive1 {  
  
    public static void main(String[] args) {  
          
        try {  
           //InetAddress address = InetAddress.getLocalHost();  
           // int port = 8954;    
              
            //创建DatagramSocket对象  
            //DatagramSocket socket = new DatagramSocket(port, address);  
        	 DatagramSocket socket = new DatagramSocket(8954);  
            byte[] buf = new byte[1024];  //定义byte数组  
            DatagramPacket packet = new DatagramPacket(buf, 1024);  //创建DatagramPacket对象  
           System.out.println("我是接受端");  
            socket.receive(packet);  //通过套接字接收数据  
              
            String getMsg = new String(packet.getData(), 0, packet.getLength())+"from"+
           packet.getAddress().getHostAddress()+":"+packet.getPort() ;  
            System.out.println("发送端发送的数据为:" + getMsg);  
            socket.close();  //关闭套接字  
              
        } catch (UnknownHostException e) {  
            e.printStackTrace();  
        } catch(IOException e) {  
            e.printStackTrace();  
        }  
    }  
}  

运行结果:

java UDP通信_第1张图片

发送端程序:

package hyz;
import java.io.IOException;  
import java.net.DatagramPacket;  
import java.net.InetAddress;  
import java.net.UnknownHostException;  
import java.net.DatagramSocket;  
  
/** 
 *  使用Sender类来代表客户端程序, 
 * @author ccna_zhang 
 * 连接特定的 DNS 后缀: 

 */  
public class UDPSend1 {  
  
    public static void main(String[] args) {  
        String msg = "Hello, 准备接收数据了吗";  
        byte[] buf = msg.getBytes();  
        try {  
            InetAddress address = InetAddress.getByName("10.240.229.90");  //接收端地址  
            int port = 8954;  //接收端的端口号  
            //创建发送方的数据报信息  
            DatagramPacket dp = new DatagramPacket(msg.getBytes(), buf.length, address, port);  
              
            DatagramSocket socket = new DatagramSocket();  //创建套接字  
            socket.send(dp);  //通过套接字发送数据  
              System.out.println("我是发送端");
            
              socket.close();  
              
        } catch (UnknownHostException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}  
运行结果:

java UDP通信_第2张图片

在接收端阻塞状态下,运行发送端程序,接收端程序会接收到数据结束阻塞。

接收端结果:




你可能感兴趣的:(java,网络编程,udp,通信,socket,java)