java建立UDP连接

Posted cappuccinom

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java建立UDP连接相关的知识,希望对你有一定的参考价值。

1. 服务器端

package com.machuang.udp;

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

public class ServerUdp {

    public static void main(String[] args) throws IOException {
        DatagramSocket server = new DatagramSocket(8888);
        
        byte[] container = new byte[1024];
        DatagramPacket packet = new DatagramPacket(container, container.length);
        
        server.receive(packet);
        
        byte[] receiveData = packet.getData();
        int len = packet.getLength();
        System.out.println(new String(receiveData, 0, len));
        
        server.close();

    }

}

2. 客户端

package com.machuang.udp;

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

public class ClientUdp {

    public static void main(String[] args) throws IOException {
        DatagramSocket client = new DatagramSocket(6666);
        
        String msg = "请求连接服务器";
        byte[] msgBytes = msg.getBytes();
        
        DatagramPacket packet = 
                new DatagramPacket(msgBytes, msgBytes.length,  new InetSocketAddress("localhost", 8888));
        
        client.send(packet);
        
        client.close();
        
        
    }

}

 

以上是关于java建立UDP连接的主要内容,如果未能解决你的问题,请参考以下文章

TCP和UDP通信有啥区别 如何分别用java实现?

java网络编程TCP/UDP笔记

TCP和UDP套接字编程 (java实现)

UDP协议通信需要建立连接吗?

Java 网络编程

JAVA本地与树莓派中采用UDP传输文本图片