UDP DatagramPacket DatagramSocket

First, UDP doesn't have any notion of a unique connection between two hosts. One socket sends and receives all data directed to or from a port without any concern for whom the remote host is. A single DatagramSocket can send data to and receive data from many independent hosts. The socket isn't dedicated to a single connection, as it is in TCP.
UDP和TCP是完全不同的概念,TCP提供了拥塞控制,提供轮包重排功能,但UDP没有这些功能,这些由应用程序自己管理(如果应用程序使用UDP),UDP的优点就是快.
================================== DatagramPacket=============================
用于存储数据( Constructors for receiving datagrams)
public DatagramPacket(byte[] buffer, int length)
public DatagramPacket(byte[] buffer, int offset, int length) // Java 1.2
如:
byte[] buffer = new byte[8192];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

Constructors for sending datagrams:
public DatagramPacket(byte[] data, int length, InetAddress destination, int port)

public DatagramPacket(byte[] data, int offset, int length, InetAddress destination, int port) // Java 1.2

public DatagramPacket(byte[] data, int length, SocketAddress destination, int port) // Java 1.4

public DatagramPacket(byte[] data, int offset, int length, SocketAddress destination, int port) // Java 1.4

如:
String s = "This is a test";
byte[] data = s.getBytes("ASCII");
try {
  InetAddress ia = InetAddress.getByName("www.ibiblio.org");
  int port = 7;
  DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
  // send the packet...
}
catch (IOException ex)
}

/*
如果DatagramPacket接收自远方这个方法返回远方的那个计算机
如果DatagramPacket在本地被创建这个方法返回要发送在哪的那个计算机
*/
public InetAddress getAddress( )
/* 和getAddress解释相似 */
public int getPort( )

public byte[] getData( ) //如:
InputStream in = new ByteArrayInputStream(packet.getData( ),
packet.getOffset( ), packet.getLength( ));
public void setData(byte[] data)
public void setAddress(InetAddress remote)
public void setPort(int port)
=============================================================================
============================= DatagramSocket==================================
This constructor creates a socket that is bound to an anonymous port. For example:
try {
  DatagramSocket client = new DatagramSocket( );
  // send packets...
}
catch (SocketException ex) {
  System.err.println(ex);
}
public DatagramSocket(int port) throws SocketException
public DatagramSocket(int port, InetAddress interface) throws SocketException

public void send(DatagramPacket dp) throws IOException
/*这个方法和ServerSocket.accept() 一样会被阻塞*/
public void receive(DatagramPacket dp) throws IOException

public void close( )

=============================================================================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值