Java网络编程、UDP案例

385人浏览 / 0人评论
发送端
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 SendUDP {
    public static void main(String[] args){
        try {
            DatagramSocket socket = new DatagramSocket();
            String str = "hello welcome to adm";
            byte[] buf = str.getBytes();
            InetAddress address = InetAddress.getByAddress(getByteIp("192.168.1.160"));
            DatagramPacket packet = new DatagramPacket(buf, buf.length,address,8888);
            socket.send(packet);
            socket.close();
             
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static byte[] getByteIp(String ip){
        byte[] ipByte = new byte[4];
        String[] strs = ip.split("\\.");
         
        for(int i = 0; i < ipByte.length; i++){
            ipByte[i] = (byte) Integer.parseInt(strs[i]);
        }
        return ipByte;
    }
}
接受端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
 
public class ReceiveUDP {
    public static void main(String[] args){
        DatagramSocket socket = null;
        DatagramPacket packet;
        byte[] buf = new byte[1024];
        try {
            socket = new DatagramSocket(8888);
            packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);
            socket.close();
            byte[] data = packet.getData();
            System.out.println(new String(data,"utf-8"));
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         
    }
}