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

}

}

}

相关推荐
OxYGC1 分钟前
[AI工程] Spring AI 第廿一篇:存量 REST 接口的 MCP 化改造实录——工具从哪条路径注册、参数描述怎么写、身份怎么过去
java·人工智能·spring
Zhou14113624 分钟前
SpringBoot_02_自动配置原理
java·spring boot·后端
m0_3807438728 分钟前
PHP7.3和7.2字符串功能有什么不同
开发语言·php
FYKJ_201031 分钟前
SSM校园失物招领系统41452-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·typescript·spark
kv11034 分钟前
Android studio国内开发有关
java·数据库·android studio
卓怡学长1 小时前
w198基于springboot始于足下健康打卡平台的设计与实现
java·spring boot·spring·intellij-idea
m0_380743871 小时前
PHP 8.4的新语法怎么用才规范
开发语言·php
阿狗童鞋1 小时前
Java并发编程实战指南
java·开发语言
别动我齐刘海1 小时前
简历技术栈全面复习——UDP / TCP / CAN / ZMQ / Protobuf 通信工程
网络·c++·python·tcp/ip·机器学习·udp·github
phltxy1 小时前
C 语言自定义类型:结构体、位段、枚举与联合体
c语言·开发语言