java UDP Socket

来源:互联网 发布:阿兴网络项目 编辑:程序博客网 时间:2024/05/29 17:37
java UDP Socket
浏览(4148)|评论(0)   交流分类:Java|笔记分类:未分类

一. UDP协议定义
UDP协议的全称是用户数据报,在网络中它与TCP协议一样用于处理数据包。在OSI模型中,在第四层——传输层,处于IP协议的上一层。UDP有不提供数据报分组、组装和不能对数据包的排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的。

二. 使用UDP的原因
它不属于连接型协议,因而具有资源消耗小,处理速度快的优点,所以通常音频、视频和普通数据在传送时使用UDP较多,因为它们即使偶尔丢失一两个数据包,也不会对接收结果产生太大影响。比如我们聊天用的ICQ和OICQ就是使用的UDP协议。在选择使用协议的时候,选择UDP必须要谨慎。在网络质量令人不十分满意的环境下,UDP协议数据包丢失会比较严重。

三. 在Java中使用UDP协议编程的相关类
1. InetAddress
用于描述和包装一个Internet IP地址。有如下方法返回实例:
getLocalhost():返回封装本地地址的实例。

getAllByName(String host):返回封装Host地址的InetAddress实例数组。

getByName(String host):返回一个封装Host地址的实例。其中,Host可以是域名或者是一个合法的IP地址。
InetAddress.getByAddress(addr):根据地址串返回InetAddress实例。
InetAddress.getByAddress(host, addr):根据主机地符串和地址串返回InetAddress实例。

2. DatagramSocket
用于接收和发送UDP的Socket实例。该类有3个构造函数:
DatagramSocket():通常用于客户端编程,它并没有特定监听的端口,仅仅使用一个临时的。程序会让操作系统分配一个可用的端口。
DatagramSocket(int port):创建实例,并固定监听Port端口的报文。通常用于服务端

DatagramSocket(int port, InetAddress localAddr):这是个非常有用的构建器,当一台机器拥有多于一个IP地址的时候,由它创建的实例仅仅接收来自LocalAddr的报文。
DatagramSocket具有的主要方法如下:
1)receive(DatagramPacket d):接收数据报文到d中。receive方法产生一个“阻塞”。“阻塞”是一个专业名词,它会产生一个内部循环,使程序暂停在这个地方,直到一个条件触发。

2)send(DatagramPacket dp):发送报文dp到目的地。

3)setSoTimeout(int timeout):设置超时时间,单位为毫秒。

4)close():关闭DatagramSocket。在应用程序退出的时候,通常会主动释放资源,关闭Socket,但是由于异常地退出可能造成资源无法回收。所以,应该在程序完成时,主动使用此方法关闭Socket,或在捕获到异常抛出后关闭Socket。

3. DatagramPacket
用于处理报文,它将Byte数组、目标地址、目标端口等数据包装成报文或者将报文拆卸成Byte数组。应用程序在产生数据包是应该注意,TCP/IP规定数据报文大小最多包含65507个,通常主机接收548个字节,但大多数平台能够支持8192字节大小的报文。DatagramPacket类的构建器共有4个:
DatagramPacket(byte[] buf, int length):将数据包中Length长的数据装进Buf数组,一般用来接收客户端发送的数据。
DatagramPacket(byte[] buf, int offset, int length):将数据包中从Offset开始、Length长的数据装进Buf数组。
DatagramPacket(byte[] buf, int length, InetAddress clientAddress, int clientPort):从Buf数组中,取出Length长的数据创建数据包对象,目标是clientAddress地址,clientPort端口,通常用来发送数据给客户端。

DatagramPacket(byte[] buf, int offset, int length, InetAddress clientAddress, int clientPort):从Buf数组中,取出Offset开始的、Length长的数据创建数据包对象,目标是clientAddress地址,clientPort端口,通常用来发送数据给客户端。
主要的方法如下:
1)getData(): 从实例中取得报文的Byte数组编码。
2)setDate(byte[] buf):将byte数组放入要发送的报文中。
四. 实例解析
下面让我们来看一个UDP的服务端和客户端交互通信的例子,在本例中,服务端循环等待客户端发送的信息,并对其进行回应,客户端向服务端发送信息,并接收服务端的回应信息。代码如下:
1.UDP的服务端程序

 

java代码:
查看复制到剪贴板打印
  1. import java.io.IOException;   
  2. import java.net.DatagramPacket;   
  3. import java.net.DatagramSocket;   
  4. import java.net.InetAddress;   
  5. import java.net.InetSocketAddress;   
  6. import java.net.SocketException;   
  7.   
  8. /**  
  9.  * Copyright 2007 GuangZhou Cotel Co. Ltd. 
  10.  * All right reserved.      
  11.  * UTP服务类.       
  12.  * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  13.  * @version 1.0   
  14.  * Creation date: 2007-8-16 - 下午10:32:31  
  15.  */  
  16. public class UdpServerSocket {   
  17.     private byte[] buffer = new byte[1024];   
  18.        
  19.     private DatagramSocket ds = null;   
  20.   
  21.     private DatagramPacket packet = null;   
  22.   
  23.     private InetSocketAddress socketAddress = null;   
  24.   
  25.     private String orgIp;   
  26.   
  27.     /**  
  28.      * 构造函数,绑定主机和端口.  
  29.      * @param host 主机  
  30.      * @param port 端口  
  31.      * @throws Exception  
  32.      */  
  33.     public UdpServerSocket(String host, int port) throws Exception {   
  34.         socketAddress = new InetSocketAddress(host, port);   
  35.         ds = new DatagramSocket(socketAddress);   
  36.         System.out.println("服务端启动!");   
  37.     }   
  38.        
  39.     public final String getOrgIp() {   
  40.         return orgIp;   
  41.     }   
  42.   
  43.     /**  
  44.      * 设置超时时间,该方法必须在bind方法之后使用.  
  45.      * @param timeout 超时时间  
  46.      * @throws Exception  
  47.      */  
  48.     public final void setSoTimeout(int timeout) throws Exception {   
  49.         ds.setSoTimeout(timeout);   
  50.     }   
  51.   
  52.     /**  
  53.      * 获得超时时间.  
  54.      * @return 返回超时时间.  
  55.      * @throws Exception  
  56.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  57.      * Creation date: 2007-8-16 - 下午10:34:36 
  58.      */  
  59.     public final int getSoTimeout() throws Exception {   
  60.         return ds.getSoTimeout();   
  61.     }   
  62.   
  63.     /**  
  64.      * 绑定监听地址和端口.  
  65.      * @param host 主机IP  
  66.      * @param port 端口  
  67.      * @throws SocketException  
  68.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  69.      * Creation date: 2007-8-16 - 下午10:36:17 
  70.      */  
  71.     public final void bind(String host, int port) throws SocketException {   
  72.         socketAddress = new InetSocketAddress(host, port);   
  73.         ds = new DatagramSocket(socketAddress);   
  74.     }   
  75.   
  76.   
  77.     /**  
  78.      * 接收数据包,该方法会造成线程阻塞.  
  79.      * @return 返回接收的数据串信息  
  80.      * @throws IOException  
  81.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  82.      * Creation date: 2007-8-16 - 下午10:38:24  
  83.      */  
  84.     public final String receive() throws IOException {   
  85.         packet = new DatagramPacket(buffer, buffer.length);   
  86.         ds.receive(packet);   
  87.         orgIp = packet.getAddress().getHostAddress();   
  88.         String info = new String(packet.getData(), 0, packet.getLength());   
  89.         System.out.println("接收信息:" + info);   
  90.         return info;   
  91.     }   
  92.   
  93.     /**  
  94.      * 将响应包发送给请求端.  
  95.      * @param bytes 回应报文  
  96.      * @throws IOException  
  97.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  98.      * Creation date: 2007-8-16 - 下午11:05:31  
  99.      */  
  100.     public final void response(String info) throws IOException {   
  101.         System.out.println("客户端地址 : " + packet.getAddress().getHostAddress()   
  102.                 + ",端口:" + packet.getPort());   
  103.         DatagramPacket dp = new DatagramPacket(buffer, buffer.length, packet   
  104.                 .getAddress(), packet.getPort());   
  105.         dp.setData(info.getBytes());   
  106.         ds.send(dp);   
  107.     }   
  108.   
  109.     /**  
  110.      * 设置报文的缓冲长度.  
  111.      * @param bufsize 缓冲长度  
  112.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  113.      * Creation date: 2007-8-16 - 下午10:47:49 
  114.      */  
  115.     public final void setLength(int bufsize) {   
  116.         packet.setLength(bufsize);   
  117.     }   
  118.   
  119.     /**  
  120.      * 获得发送回应的IP地址.  
  121.      * @return 返回回应的IP地址  
  122.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  123.      * Creation date: 2007-8-16 - 下午10:48:27 
  124.      */  
  125.     public final InetAddress getResponseAddress() {   
  126.         return packet.getAddress();   
  127.     }   
  128.   
  129.     /**  
  130.      * 获得回应的主机的端口.  
  131.      * @return 返回回应的主机的端口.  
  132.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  133.      * Creation date: 2007-8-16 - 下午10:48:56 
  134.      */  
  135.     public final int getResponsePort() {   
  136.         return packet.getPort();   
  137.     }   
  138.   
  139.     /**  
  140.      * 关闭udp监听口.  
  141.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  142.      * Creation date: 2007-8-16 - 下午10:49:23  
  143.      */  
  144.     public final void close() {   
  145.         try {   
  146.             ds.close();   
  147.         } catch (Exception ex) {   
  148.             ex.printStackTrace();   
  149.         }   
  150.     }   
  151.   
  152.     /**  
  153.      * 测试方法.  
  154.      * @param args  
  155.      * @throws Exception  
  156.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  157.      * Creation date: 2007-8-16 - 下午10:49:50 
  158.      */  
  159.     public static void main(String[] args) throws Exception {   
  160.         String serverHost = "127.0.0.1";   
  161.         int serverPort = 3344;   
  162.         UdpServerSocket udpServerSocket = new UdpServerSocket(serverHost, serverPort);   
  163.         while (true) {   
  164.             udpServerSocket.receive();   
  165.             udpServerSocket.response("你好,sterning!");   
  166.                
  167.         }   
  168.     }   
  169. }  

 

2. UDP客户端程序

 

java代码:
查看复制到剪贴板打印
  1. import java.io.*;   
  2. import java.net.*;   
  3.   
  4. /**  
  5.  * Copyright 2007 GuangZhou Cotel Co. Ltd. 
  6.  * All right reserved.      
  7.  * UDP客户端程序,用于对服务端发送数据,并接收服务端的回应信息.  
  8.  * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  9.  * @version 1.0   
  10.  * Creation date: 2007-8-16 - 下午10:54:23  
  11.  */  
  12. public class UdpClientSocket {   
  13.     private byte[] buffer = new byte[1024];   
  14.   
  15.     private DatagramSocket ds = null;   
  16.   
  17.     /**  
  18.      * 构造函数,创建UDP客户端  
  19.      * @throws Exception  
  20.      */  
  21.     public UdpClientSocket() throws Exception {   
  22.         ds = new DatagramSocket();   
  23.     }   
  24.        
  25.     /**  
  26.      * 设置超时时间,该方法必须在bind方法之后使用.  
  27.      * @param timeout 超时时间  
  28.      * @throws Exception  
  29.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  30.      * Creation date: 2007-8-16 - 下午10:55:12  
  31.      */  
  32.     public final void setSoTimeout(final int timeout) throws Exception {   
  33.         ds.setSoTimeout(timeout);   
  34.     }   
  35.   
  36.     /**  
  37.      * 获得超时时间.  
  38.      * @return 返回超时时间  
  39.      * @throws Exception  
  40.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  41.      * Creation date: 2007-8-16 - 下午10:55:25 
  42.      */  
  43.     public final int getSoTimeout() throws Exception {   
  44.         return ds.getSoTimeout();   
  45.     }   
  46.   
  47.     public final DatagramSocket getSocket() {   
  48.         return ds;   
  49.     }   
  50.   
  51.     /**  
  52.      * 向指定的服务端发送数据信息.  
  53.      * @param host 服务器主机地址  
  54.      * @param port 服务端端口  
  55.      * @param bytes 发送的数据信息  
  56.      * @return 返回构造后俄数据报  
  57.      * @throws IOException  
  58.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  59.      * Creation date: 2007-8-16 - 下午11:02:41 
  60.      */  
  61.     public final DatagramPacket send(final String host, final int port,   
  62.             final byte[] bytes) throws IOException {   
  63.         DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress   
  64.                 .getByName(host), port);   
  65.         ds.send(dp);   
  66.         return dp;   
  67.     }   
  68.   
  69.     /**  
  70.      * 接收从指定的服务端发回的数据.  
  71.      * @param lhost 服务端主机  
  72.      * @param lport 服务端端口  
  73.      * @return 返回从指定的服务端发回的数据.  
  74.      * @throws Exception  
  75.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  76.      * Creation date: 2007-8-16 - 下午10:52:36  
  77.      */  
  78.     public final String receive(final String lhost, final int lport)   
  79.             throws Exception {   
  80.         DatagramPacket dp = new DatagramPacket(buffer, buffer.length);   
  81.         ds.receive(dp);   
  82.         String info = new String(dp.getData(), 0, dp.getLength());   
  83.         return info;   
  84.     }   
  85.   
  86.     /**  
  87.      * 关闭udp连接.  
  88.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  89.      * Creation date: 2007-8-16 - 下午10:53:52 
  90.      */  
  91.     public final void close() {   
  92.         try {   
  93.             ds.close();   
  94.         } catch (Exception ex) {   
  95.             ex.printStackTrace();   
  96.         }   
  97.     }   
  98.   
  99.     /**  
  100.      * 测试客户端发包和接收回应信息的方法.  
  101.      * @param args  
  102.      * @throws Exception  
  103.      * @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  104.      * Creation date: 2007-8-16 - 下午11:03:54  
  105.      */  
  106.     public static void main(String[] args) throws Exception {   
  107.         UdpClientSocket client = new UdpClientSocket();   
  108.         String serverHost = "127.0.0.1";   
  109.         int serverPort = 3344;   
  110.         client.send(serverHost, serverPort, ("你好,阿蜜果!").getBytes());   
  111.         String info = client.receive(serverHost, serverPort);   
  112.         System.out.println("服务端回应数据:" + info);   
  113.     }   
  114. }  



原创粉丝点击