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 byte1024;

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();

}

}

}

相关推荐
深入云栈1 小时前
CompleteFuture VS CompletableFuture:Netty 为何自研 Future
java·架构
OPEN-F1 小时前
C++综合实战:面向对象图书管理系统
开发语言·c++
ttwuai1 小时前
Go 后台清空操作日志失败,权限和无 WHERE 删除怎么排查?
开发语言·后端·golang
choumou_M2 小时前
SpringBoot_7:用户资源的上传与修改
java·spring boot·后端
西西弗Sisyphus2 小时前
Qt 在无边框窗口上做一套换肤系统
开发语言·数据库·qt
西西弗Sisyphus2 小时前
Qt 启动 UsageStatistic 插件报错
开发语言·qt
NeoGressAI外贸数字化2 小时前
外贸独立站零询盘排查:从 Google Search Console 到 PageSpeed 的技术实操
开发语言·c++
无小道2 小时前
C/C++——异步编程小记
开发语言·c++·c++11
奇树谦2 小时前
Pimpl 模式(d-pointer)详解:如何解决 C++ 头文件过大、编译依赖和 ABI 兼容问题
开发语言·c++
user_admin_god2 小时前
一体化数据归集接口详细设计说明
java·大数据·spring boot·后端·spring