java实现udp客户端

import java.net.*;

public class UdpClient {

public static void main(String[] args) throws Exception {

// 定义服务器地址和端口号

String serverAddress = "127.0.0.1";

int serverPort = 8888;

// 创建数据包对象并设置要发送的消息内容

byte[] sendData = "Hello Server!".getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName(serverAddress), serverPort);

// 创建UDP Socket对象

DatagramSocket socket = new DatagramSocket();

try {

// 向服务器发送数据包

socket.send(sendPacket);

// 接收从服务器返回的数据包

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

socket.receive(receivePacket);

// 打印服务器返回的消息内容

System.out.println("Received message from server: " + new String(receivePacket.getData(), 0, receivePacket.getLength()));

} finally {

// 关闭socket连接

socket.close();

}

}

}

相关推荐
FrankYoou13 分钟前
Jenkins 与 GitLab CI/CD 的核心对比
java·docker
麦兜*39 分钟前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
Coding小公仔1 小时前
C++ bitset 模板类
开发语言·c++
KK溜了溜了1 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
小赖同学啊1 小时前
物联网数据安全区块链服务
开发语言·python·区块链
天河归来1 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
shimly1234561 小时前
bash 脚本比较 100 个程序运行时间,精确到毫秒,脚本
开发语言·chrome·bash
weixin_478689761 小时前
十大排序算法汇总
java·算法·排序算法
码荼1 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud