UDP server & client

 

Server:

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

public class UDPServerTest {

    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(9954);

        byte[] data = new byte[512];
        DatagramPacket dp = new DatagramPacket(data, data.length);

        while (true) {
            ds.receive(dp);

            System.out.println("receive:");
            System.out.println(dp.getSocketAddress());
            System.out.println(new String(data, "UTF-8"));

            //response
            String st = "qnmlgb~hi!";
            byte[] bytes = st.getBytes();
            DatagramPacket response = new DatagramPacket(bytes, bytes.length,
                dp.getSocketAddress());
            ds.send(response);
        }
    }

}

 

Client:

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

public class UDPClientTest {

    public static InetSocketAddress localServer = new InetSocketAddress("127.0.0.1", 9954);

    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();
        String st = "loull~hi!";
        byte[] data = st.getBytes();
        DatagramPacket dp = new DatagramPacket(data, data.length, localServer);
        ds.send(dp);

        int localPort = ds.getLocalPort();
        System.out.println("localport:" + localPort);

        byte[] buf = new byte[512];
        DatagramPacket receive = new DatagramPacket(buf, buf.length);
        ds.receive(receive);
        String response = new String(receive.getData(), 0, receive.getLength());
        System.out.println("response:" + response);
    }

}

 

你可能感兴趣的:(UDP server & client)