Java之UDP编程浅析
发布日期:2021-05-27 02:54:24 浏览次数:29 分类:技术文章

本文共 4549 字,大约阅读时间需要 15 分钟。

一. UDP协议发送数据:

  1.  创建发送端socket对象
  2.  创建数据并把数据打包
  3.  调用socket对象的发送方法发送数据包
  4.  释放资源

二. UDP协议接收数据:

  1. 创建发送端socket对象(需要指定端口)
  2. 创建一个数据包(接收容器) 
  3. 调用socket对象的接收方法接收数据
  4. 解析数据并显示在控制台
  5. 释放资源

UDP协议不需要建立连接,实例如下:

 

public class UdpServer {    public static void main(String[] args) {        try {            DatagramSocket datagramSocket = new DatagramSocket(10000);            byte[] buf = new byte[1024];            DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);            while (true) {                datagramSocket.receive(datagramPacket);                System.out.println("ip:" + datagramPacket.getAddress().getHostAddress());                System.out.println("接收信息:" + new String(datagramPacket.getData(), 0, datagramPacket.getLength()));            }        } catch (SocketException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}public class UdpClient {    public static void main(String[] args) {        try {            DatagramSocket datagramSocket = new DatagramSocket();            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));            System.out.println("请输入:");            String line = null;            while ((line = reader.readLine()) != null) {                byte[] bytes = line.getBytes();                DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("127.0.0.1"), 10000);                // 发送数据                datagramSocket.send(datagramPacket);                datagramSocket.close();            }        } catch (UnknownHostException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}
public class UdpUtil {    public DatagramSocket socketServer = null;    private String ip;    private int serverPort;    public UdpUtil() {    }    public UdpUtil(int serverPort) {        this.serverPort = serverPort;    }    public UdpUtil(String ip, int serverPort) {        this.ip = ip;        this.serverPort = serverPort;    }    public void connect() throws Exception {        try {            if (socketServer != null) {                socketServer.close();            }            socketServer = new DatagramSocket(serverPort);            socketServer.setReceiveBufferSize(1024 * 200);            System.out.println("UDPServer connect success.");        } catch (Exception e) {            if (socketServer != null) {                socketServer.close();                socketServer = null;            }            throw new Exception("Connect failed. " + e.getMessage());        }    }    public void connect(int port) throws Exception {        try {            if (socketServer != null) {                socketServer.close();            }            socketServer = new DatagramSocket(port);            socketServer.setReceiveBufferSize(1024 * 200);            System.out.println("UDPServer connect success.");        } catch (SocketException e) {            if (socketServer != null) {                socketServer.close();                socketServer = null;            }            throw new Exception("Connect failed." + e.getMessage());        }    }    public DatagramPacket collectDatagramPacket(int dataLength) throws IOException {        byte[] data = new byte[dataLength];        DatagramPacket dPacket = new DatagramPacket(data, dataLength);        socketServer.receive(dPacket);        return dPacket;    }    public byte[] collect(int dataLength) throws IOException {        byte[] data = new byte[dataLength];        DatagramPacket dPacket = new DatagramPacket(data, dataLength);        socketServer.receive(dPacket);        return data;    }    public byte[] collect(int dataLength, String ip1, String ip2) throws Exception {        byte[] data = new byte[dataLength];        DatagramPacket dPacket = new DatagramPacket(data, dataLength);        socketServer.receive(dPacket);        if (ip1 != null || ip2 != null) {            if (dPacket.getAddress().getHostAddress().equals(ip1) || dPacket.getAddress().getHostAddress().equals(ip2)) {                return data;            } else {                return null;            }        } else {            return data;        }    }    public void send(DatagramPacket datagramPacket) throws Exception {        socketServer.send(datagramPacket);    }    public void send(byte[] data) throws IOException {        DatagramPacket datagramPacket = new DatagramPacket(data, data.length, InetAddress.getByName(ip), serverPort);        socketServer.send(datagramPacket);    }}

 

转载地址:https://blog.csdn.net/leijie0322/article/details/115146959 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java之proto初尝试
下一篇:Java中ThreadLocal浅析

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年09月23日 08时12分21秒