廖雪峰Java13网络编程-1Socket编程-5UDP编程

1. UDP编程:

  • 不需要建立连接
  • 可以直接发送和接收数据

1.1 客户端

    DatagramSocket sock = new DatagramSocket(){}
    sock.connect(addr,9090);//并不建立连接
    //接收
    byte[] data=...;
    DatagramPacket packet = new DatagramPacket(data, data.length);
    sock.send(packet);
    //发送
    byte[] buffer = new byte[1024];
    DatagramPacket resp = new DatagramPacket(buffer, buffer.length);
    sock.receive(resp);
    //接收和发送都是通过DatagramPacket实现的

1.2 服务端:

    DatagramSocket ds = new DatagramSocket(9090);
    for( ; ; ){
        //接收
        byte[] buffer = new buffer[1024];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        ds.receive(packet);
        //发送
        byte[] data = ...;
        packet.setData(data);
        ds.send(packet);
    }

1.3 实例

TCPClient.java

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

public class UDPClient {
    public static void main(String[] args) throws Exception{
        InetAddress addr = InetAddress.getLoopbackAddress();
        try(DatagramSocket sock = new DatagramSocket()){
            sock.connect(addr,9090);
            byte[] data = "time".getBytes(StandardCharsets.UTF_8);
            DatagramPacket packet = new DatagramPacket(data,data.length);
            sock.send(packet);
            System.out.println("Data was sent");
            Thread.sleep(1000);
            byte[] buffer = new byte[1024];
            DatagramPacket resp = new DatagramPacket(buffer,buffer.length);
            sock.receive(resp);
            byte[] respData = resp.getData();
            String respText = new String(respData,0,resp.getLength());
            System.out.println("Response:"+respText);
        }
    }
}

TCPServer.java

package com.crazy;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

public class UDPServer {
    public LocalDateTime currentTime(){
        return LocalDateTime.now();
    }
    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket(9090);
        System.out.println("UDP server ready");
        for(;;){
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
            ds.receive(packet);
            byte[] data = packet.getData();
            String s = new String(data, StandardCharsets.UTF_8);
            System.out.println("Pack received from : "+packet.getSocketAddress());
            String resp = LocalDateTime.now().toString();
            packet.setData(resp.getBytes(StandardCharsets.UTF_8));
            ds.send(packet);
        }
    }
}

先运行server

再运行client

2. 总结:

UDP编程模型:

  • 客户端使用DatagramSocket.connect()指定远程地址和端口
  • 服务器端用DatagramSocket(port)监听端口
  • 双方通过receive/send读写数据
  • 没有IO流接口
posted on 2019-07-07 14:02  singleSpace  阅读(240)  评论(0编辑  收藏  举报