欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java UDP传输

程序员文章站 2022-04-08 23:18:27
...
TCP通过 ServerSocket 和 Socket 来实现传输

UDP主要通过 DatagramSocket 和 DatagramPacket 来完成传输

直接上代码

服务器端:
# public class UdpServer  
# {  
#     private DatagramSocket server;  
#   
#     private DatagramPacket packet;  
#   
#     private byte[] b;  
#   
#     private String str;  
#   
#     public UdpServer()  
#     {  
#         Init();  
#     }  
#   
#     private void Init()  
#     {  
#           
#         b = new byte[1024];  
#           
#         receive();  
#     }  
#   
#     private void receive()  
#     {  
#         try  
#         {  
#             server=new DatagramSocket(11111); //绑定11111端口  
#   
#             while(true)  
#             {  
#                 packet = new DatagramPacket(b, b.length);  
#   
#                 server.receive(packet); //接收数据包  
#   
#                 int i = packet.getLength();  
#   
#                 if(i>0) //数据包有内容,就打印出接收到的数据  
#                 {  
#                     str = new String(b, 0, i);  
#                     System.out.println("接收到的字符 == " + str);   
#                     packet = null;   
#                 }  
#             }     
#         }catch(SocketException e)  
#         {  
#             e.printStackTrace();  
#         }catch(IOException e)  
#         {  
#             e.printStackTrace();  
#         }finally  
#         {  
#             server.close();  
#         }  
#     }  
#   
#     public static void main(String[] args)  
#     {  
#         new UdpServer();  
#     }  
# }


客户端:
# public class UdpClient  
# {  
#     private DatagramSocket client;  
#   
#     private DatagramPacket packet;  
#   
#     private byte b[];  
#   
#     public UdpClient()  
#     {  
#         Init();  
#     }  
#   
#     private void Init()  
#     {  
#         b = new byte[1024];  
#           
#         send();  
#     }  
#   
#     private void send()  
#     {  
#         try  
#         {  
#             client = new DatagramSocket();  
#               
#             b = "UDP数据发送".getBytes(); //发送给服务器端的数据  
#               
#             packet = new DatagramPacket(b, b.length, new InetSocketAddress("127.0.0.1", 11111)); //绑定服务器  
#             client.send(packet); //发送数据包  
#         } catch (SocketException e)  
#         {  
#             e.printStackTrace();  
#         } catch (IOException e)  
#         {  
#             e.printStackTrace();  
#         } finally  
#         {  
#             client.close();  
#         }  
#     }  
#   
#     public static void main(String[] args)  
#     {  
#         new UdpClient();  
#     }  
# }
相关标签: Java Socket