【Java】UDP发包的简单实现

发布时间:2019-11-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【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:384754419,请注明来意。