简单的UDP程序
Posted 静! 非淡泊无以明志,非宁静无以致远!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的UDP程序相关的知识,希望对你有一定的参考价值。
接受端:
package com.dcz.udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class Receive { public static void main(String[] args) throws IOException { DatagramSocket receive = new DatagramSocket(17002); byte[] buf = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buf, 1024); receive.receive(datagramPacket); String str = new String(datagramPacket.getData(), 0 , datagramPacket.getLength()); System.out.println("接受数据:" + str); receive.close(); } }
发送端:
package com.dcz.udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Send { public static void main(String[] args) throws IOException { String data = "带发送的数据!"; DatagramSocket send = new DatagramSocket(17006); DatagramPacket datagramPacket = new DatagramPacket( data.getBytes(), data.getBytes().length, InetAddress.getLocalHost(), 17002); send.send(datagramPacket); send.close(); } }
以上是关于简单的UDP程序的主要内容,如果未能解决你的问题,请参考以下文章