JAVA网络编程UDP案例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA网络编程UDP案例相关的知识,希望对你有一定的参考价值。
Java网络编程、UDP案例
发送端
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class SendUDP { public static void main(String[] args){ try { DatagramSocket socket = new DatagramSocket(); String str = "hello welcome to adm"; byte[] buf = str.getBytes(); InetAddress address = InetAddress.getByAddress(getByteIp("192.168.1.160")); DatagramPacket packet = new DatagramPacket(buf, buf.length,address,8888); socket.send(packet); socket.close(); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static byte[] getByteIp(String ip){ byte[] ipByte = new byte[4]; String[] strs = ip.split("\\."); for(int i = 0; i < ipByte.length; i++){ ipByte[i] = (byte) Integer.parseInt(strs[i]); } return ipByte; } }
接收端
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class ReceiveUDP { public static void main(String[] args){ DatagramSocket socket = null; DatagramPacket packet; byte[] buf = new byte[1024]; try { socket = new DatagramSocket(8888); packet = new DatagramPacket(buf, buf.length); socket.receive(packet); socket.close(); byte[] data = packet.getData(); System.out.println(new String(data,"utf-8")); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
本文出自 “生命不息,折腾不止” 博客,请务必保留此出处http://admxj.blog.51cto.com/10955090/1739665
以上是关于JAVA网络编程UDP案例的主要内容,如果未能解决你的问题,请参考以下文章