脚本宝典收集整理的这篇文章主要介绍了

【Java】UDP发包的简单实现

脚本宝典小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助你少写一行代码,多一份安全和惬意。

最近在学Java,正好做一些笔记,以防止自己忘了。


client端

//UdpClient.java import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException;   public class UdpClient {     private static DatagramSocket clientSocket = null;     private InetSocketAddress serverAddress = null;      public UdpClient(String host, int port) throws SocketException {         clientSocket = new DatagramSocket( );           //创建socket                 serverAddress = new InetSocketAddress(host, port);  //绑定sever的ip与port     }       public void send(String msg) throws IOException {         try {             byte[] data = msg.getBytes("utf-8");                DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress);             clientSocket.send(packet);         } catch (UnsupportedEncodingException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }     }      //main方法用于测试     public static void main(String[] args) throws Exception {           UdpClient client = new UdpClient("127.0.0.1", 14586);         client.send("hello world");         clientSocket.close();     } } 

server端

//UdpServer.java import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException;   public class UdpServer {     private byte[] data = new byte[1024];     private static DatagramSocket serverSocket = null;     private DatagramPacket packet = null;      public UdpServer(int port) throws SocketException {         serverSocket = new DatagramSocket(port);         System.out.println("sever start!");     }      //接收消息     public String recieve() throws IOException {         packet = new DatagramPacket(data, data.length);         serverSocket.receive(packet);         String info = new String(packet.getData(), 0, packet.getLength());         System.out.println("recieve message from " + packet.getAddress().getHostAddress()                 + ":" + packet.getPort() + "t"+ info);         return info;     }      //本地测试     public static void main(String[] args) throws Exception {         UdpServer server = new UdpServer(14586);         server.recieve();        } } 

打印结果

sever start!
recieve message from 127.0.0.1:64478 hello world

总结

以上是脚本宝典为你收集整理的

【Java】UDP发包的简单实现

全部内容,希望文章能够帮你解决

【Java】UDP发包的简单实现

所遇到的程序开发问题,欢迎加入QQ群277859234一起讨论学习。如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典网站推荐给程序员好友。 本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。

80%的人都看过