Java网络编程---UDP

客户端

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws Exception {
        //1.创建客户端对象
        DatagramSocket socket = new DatagramSocket();
        //2.创建数据包对象封装要发出去的数据
        /* public DatagramPacket(byte buf[], int offset, int length,
        InetAddress address, int port)*/
        Scanner sc = new Scanner(System.in);
        while (true){
            //将数据转成字节
            System.out.println("user:");
            String msg = sc.nextLine();
            if ("exit".equals(msg)){
                System.out.println("退出成功!");
                socket.close();
                break;
            }
            byte[] bytes =msg.getBytes();
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length,InetAddress.getLocalHost(),6666);
            //3.发送
            socket.send(packet);
        }
    }
}

服务端

import java.nio.charset.StandardCharsets;


import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Server {
    public static void main(String[] args) throws Exception{
        System.out.println("----------服务端-----------");
        //1.创建一个服务端的对象
        DatagramSocket socket = new DatagramSocket(6666);

        //2.创建一个数据包对象  来接数据
        byte[] buffer = new byte[1024 * 64]; //64kb
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        while (true){
            //接收数据
            socket.receive(packet);

            //打印出来
            int len = packet.getLength();
            String  rs =  new String(buffer,0,len, StandardCharsets.UTF_8);
            System.out.println(rs);


            //接收的客户端的信息
            System.out.println(packet.getAddress());
            System.out.println(packet.getPort());
            System.out.println("-----------------------------------------");
        }

    }
}

效果

Java网络编程---UDP_第1张图片

你可能感兴趣的:(网络,java,udp)