夜光 带你走进 Java基础编程实战(三十一 tcp/udp)

夜光序言:

只有当你认真地去做一件事的时候,才会发现自己的灵魂,和灵魂深处~~

夜光 带你走进 Java基础编程实战(三十一 tcp/udp)

 

 

正文:

第一个类,接受类


import java.net.*;
public class UdpRecv

// 夜光  这个类里面主要是接收方~~

{
    public static void main(String[] args) throws Exception
    {
        DatagramSocket    ds=new DatagramSocket(3000);
        byte [] buf=new byte[1024];
        DatagramPacket dp=new DatagramPacket(buf,1024);
        
        System.out.println("UdpRecv: 夜光在等待信息");
        ds.receive(dp);
        System.out.println("UdpRecv: 夜光接收到信息");
        String strRecv=new String(dp.getData(),0,dp.getLength()) +
        " from " + dp.getAddress().getHostAddress()+":"+dp.getPort(); 
        System.out.println(strRecv);
        
        Thread.sleep(1000);
        System.out.println("UdpRecv: 夜光要发送信息");
        String str="hello Genius";
        DatagramPacket dp2=new DatagramPacket(str.getBytes(),str.length(), 
                InetAddress.getByName("127.0.0.1"),dp.getPort());
        ds.send(dp2);
        System.out.println("UdpRecv: 夜光发送信息结束");
        ds.close();
    }
}

 

第二个类,发送类

 

import java.net.*;
public class UdpSend
{
    public static void main(String [] args) throws Exception
    {
        DatagramSocket ds=new DatagramSocket();
        String str="hello Genius";
        DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),
                InetAddress.getByName("127.0.0.1"),3000);
        
        System.out.println("UdpSend: 夜光要发送信息");
        ds.send(dp);
        System.out.println("UdpSend: 夜光发送信息结束");
        
        Thread.sleep(1000);
        byte [] buf=new byte[1024];
        DatagramPacket dp2=new DatagramPacket(buf,1024);
        System.out.println("UdpSend: 我在等待信息");
        ds.receive(dp2);
        System.out.println("UdpSend: 我接收到信息");
        String str2=new String(dp2.getData(),0,dp2.getLength()) +
                " from " + dp2.getAddress().getHostAddress()+":"+dp2.getPort(); 
        System.out.println(str2);
                
        ds.close();
    }
}

 

 

运行结果:

夜光 带你走进 Java基础编程实战(三十一 tcp/udp)

夜光 带你走进 Java基础编程实战(三十一 tcp/udp)