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(); } }
原文地址:https://www.cnblogs.com/cappuccinom/p/8805310.html
时间: 2024-10-27 02:57:00