Home > Java > javaTutorial > body text

How to send data via UDP in java

WBOY
Release: 2023-05-01 08:43:06
forward
1454 people have browsed it

1. Sending steps

Create the Socket object (DatagramSocket) of the sending end

Create data and package the data

Call the DatagramSocket object Method to send data

Close the sending end

2, instance

import java.net.*;
import java.io.*;
 
class  Send
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();//通过DatagramSocket对象创建udp服务
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));//从键盘上面输入文本
String line = null;
while((line=bufr.readLine())!=null)//当输入不为空时
{
if("byebye".equals(line))//当输入为byebye时退出程序
break;
//确定好数据后,并把数据封装成数据包
byte[] buf = line.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("10.32.0.23"),30000);//发送至指定IP,指定端口
ds.send(dp);//通过send方法将数据包发送出去
}
ds.close();//关闭资源
}
}
Copy after login

The above is the detailed content of How to send data via UDP in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!