UDP编程:

具体使用packet和socket完成

1.DatagramSocket与DatagramPacket

2.创建发送端,接收端

3.创建数据报,用于存储数据

4.调用Socket的发送,接受方法

5.关闭Socket

发送端和输出端是两个独立的运行程序:

发送端:

public class send {

    public static void main(String[] args) {
        try{
            DatagramSocket datagramSocket= new DatagramSocket();
            byte[] bytes="你好接收端".getBytes();//发送的数据
            //封装一个数据报
            DatagramPacket datagramPacket= new DatagramPacket(bytes,0,bytes.length,InetAddress.getByName("186.192.153.144"),5555);
            //引号内数字是电脑的地址,后面数字则是输出和接收两端匹配的密码
            datagramSocket.send(datagramPacket);
            datagramSocket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        }catch(UnknownHostException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }}

接收端:

 public static void main(String[] args) {
        try {
            ServerSocket serverSocket=new ServerSocket(5555);
            System.out.println("服务器启动成功");
            Socket socket = serverSocket.accept();
            System.out.println("有客户连接到了服务器");

            InputStream inputstream= socket.getInputStream();

            DataInputStream dataInputstream = new DataInputStream(inputstream);
            String s = dataInputstream.readUTF() ;
            System.out.println("客户端说:"+s);

            OutputStream outputstream = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputstream);
            Scanner scanner=new Scanner(System.in);
            System.out.println("服务器端输入:");
            String s1 = scanner.next();
            dataOutputStream.writeUTF(s1);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务器启动失败,端口被占用");
        }
    }

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