Java Udp Socket Simple Demo

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

public class server {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8080);
        byte[] data = new byte[1024];
        DatagramPacket packet = new DatagramPacket(data, data.length);
        socket.receive(packet);
        String info = new String(data, 0, packet.getLength());
        System.out.println("client:" + info);
        InetAddress address = packet.getAddress();
        int port = packet.getPort();
        byte[] data2 = "Hello Client!".getBytes();
        DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, port);
        socket.send(packet2);
        socket.close();
    }
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class client {
    public static void main(String[] args) throws IOException {
        
        InetAddress address = InetAddress.getByName("127.0.0.1");
        int port = 8080;
        byte[] data = "Hello Server!".getBytes();
        DatagramPacket packetSend = new DatagramPacket(data, data.length, address, port);
        DatagramSocket socket = new DatagramSocket(8888);
        socket.send(packetSend);
        byte[] dataRecv = new byte[1024];
        DatagramPacket packetRecv = new DatagramPacket(dataRecv, dataRecv.length);
        socket.receive(packetRecv);
        String reply = new String(dataRecv, 0, packetRecv.getLength());
        System.out.println("server:" + reply);
        socket.close();
    }
}

 

你可能感兴趣的:(Java Udp Socket Simple Demo)