Java Networking: UDP DatagramSocket (翻译)

原文:http://tutorials.jenkov.com/java-networking/udp-datagram-sockets.html
  • UDP vs. TCP
  • Sending Data via a DatagramSocket
  • Receiving Data via a DatagramSocket

DatagramSocket‘s are Java‘s mechanism for network communication via UDP instead of TCP. UDP is still layered ontop of IP. You can use Java‘s DatagramSocket both for sending and receiving UPD datagrams.

DatagramSocket类 是采用java网络通信机制中的UDP而不是TCP。UDP仍位于IP层的上面。 你可以用DatagramSocket类发送和接收UDP数据包

UDP vs. TCP

UDP works a bit differently from TCP. When you send data via TCP you first create a connection. Once the TCP connection is established TCP guarantess that your data arrives at the other end, or it will tell you that an error occurred.

With UDP you just send packets of data (datagrams) to some IP address on the network. You have no guarantee that the data will arrive. You also have no guarantee about the order which UDP packets arrive in at the receiver. This means that UDP has less protocol overhead (no stream integrity checking) than TCP.

UDP is appropriate for data transfers where it doesn‘t matter if a packet is lost in transition. For instance, imagine a transfer of a live TV-signal over the internet. You want the signal to arrive at the clients as close to live as possible. Therefore, if a frame or two are lost, you don‘t really care. You don‘t want the live broadcast to be delayed just to make sure all frames are shown at the client. You‘d rather skip the missed frames, and move directly to the newest frames at all times.

This could also be the case with a surveillance camera broadcasting over the internet. Who cares what happened in the past, when you are trying to monitor the present. You don‘t want to end up being 30 seconds behind reality, just because you want to show all frames to the person monitoring the camera. It is a bit different with the storage of the camera recordings. You may not want to lose a single frame when recording the images from the camera to disk. You may rather want a little delay, than not have those frames to go back and examine, if something important occurs.

Sending Data via a DatagramSocket

To send data via Java‘s DatagramSocket you must first create a DatagramPacket. Here is how that is done:

byte[] buffer = new byte[65508];
InetAddress address = InetAddress.getByName("jenkov.com");

DatagramPacket packet = new DatagramPacket(
    buffer, buffer.length, address, 9000);

The byte buffer (the byte array) is the data that is to be sent in the UDP datagram. The length of the above buffer, 65508 bytes, is the maximum amount of data you can send in a single UDP packet.

The length given to the DatagramPacket constructor is the length of the data in the buffer to send. All data in the buffer after that amount of data is ignored.

The InetAddress instance contains the address of the node (e.g. server) to send the UDP packet to. TheInetAddress class represents an IP address (Internet Address). The getByName() method returns an InetAddressinstance with the IP address matching the given host name.

The port parameter is the UDP port the server to receiver the data is listeing on. UDP and TCP ports are not the same. A computer can have different processes listening on e.g. port 80 in UDP and in TCP at the same time.

To send the DatagramPacket you must create a DatagramSocket targeted at sending data. Here is how that is done:

DatagramSocket datagramSocket = new DatagramSocket();

To send data you call the send() method, like this:

datagramSocket.send(packet);

Here is a full example:

DatagramSocket datagramSocket = new DatagramSocket();

byte[] buffer = "0123456789".getBytes();
InetAddress receiverAddress = InetAddress.getLocalHost();

DatagramPacket packet = new DatagramPacket(
        buffer, buffer.length, receiverAddress, 80);
datagramSocket.send(packet);

Receiving Data via a DatagramSocket

Receiving data via a DatagramSocket is done by first creating a DatagramPacket and then receiving data into it via the DatagramSocket‘s receive() method. Here is an example:

DatagramSocket datagramSocket = new DatagramSocket(80);

byte[] buffer = new byte[10];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

datagramSocket.receive(packet);

Notice how the DatagramSocket is instantiated with the parameter value 80 passed to its constructor. This parameter is the UDP port the DatagramSocket is to receive UDP packets on. As mentioned earlier, TCP and UDP ports are not the same, and thus do not overlap. You can have two different processes listening on both TCP and UDP port 80, without any conflict.

Second, a byte buffer and a DatagramPacket is created. Notice how the DatagramPacket has no information about the node to send data to, as it does when creating a DatagramPacket for sending data. This is because we are going to use the DatagramPacket for receiving data, not sending it. Thus no destination address is needed.

Finally the DatagramSocket‘s receive() method is called. This method blocks until a DatagramPacket is received.

The data received is located in the DatagramPacket‘s byte buffer. This buffer can be obtained by calling:

byte[] buffer = packet.getData();

How much data was received in the buffer is up to you to find out. The protocol you are using should specify either how much data is sent per UDP packet, or specify an end-of-data marker you can look for instead.

A real server program would probably call the receive() method in a loop, and pass all receivedDatagramPacket‘s to a pool of worker threads, just like a TCP server does with incoming connections (seeJava Multithreaded Servers for more details).

Next: Java Networking: URL + URLConnection

时间: 2024-10-07 02:43:29

Java Networking: UDP DatagramSocket (翻译)的相关文章

java之UDP(datagramsocket,datagramPacket)实例

import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import org.junit.Test; public class TestUDP { @Test public voi

Java Networking

1 Java Networking 2 Java Networking: Socket 3 Java Networking: ServerSocket 4 Java Networking: UDP DatagramSocket 5 Java Networking: URL + URLConnection 6 Java Networking: JarURLConnection 7 Java Networking: InetAddress 8 Java Networking: Protocol De

Java Networking: Socket

Java Networking 1 Java Networking 2 Java Networking: Socket 3 Java Networking: ServerSocket 4 Java Networking: UDP DatagramSocket 5 Java Networking: URL + URLConnection 6 Java Networking: JarURLConnection 7 Java Networking: InetAddress 8 Java Network

java使用UDP

Java中通信可以使用的协议包括TCP协议和UDP协议 UDP协议概念 UDP协议的全称是用户数据报协议 ,在网络中它与TCP协议一样用于处理数据包,但它是一种无连接的协议.在OSI模型中,在第四层--传输层,处于IP协议的上一层.UDP有不提供数据包分组.组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的. 综上所述:UDP不提供可靠地保证,保证数据准确按序到达目的地 为什么要使用UDP 在选择使用协议的时候,选择UDP必须要谨慎?在网络质量令人不十分满

Java TCP/UDP socket 编程流程总结

最近正好学习了一点用java socket编程的东西.感觉整体的流程虽然不是很繁琐,但是也值得好好总结一下. Socket Socket可以说是一种针对网络的抽象,应用通过它可以来针对网络读写数据.就像通过一个文件的file handler就可以都写数据到存储设备上一样.根据TCP协议和UDP协议的不同,在网络编程方面就有面向两个协议的不同socket,一个是面向字节流的一个是面向报文的. 对socket的本身组成倒是比较好理解.既然是应用通过socket通信,肯定就有一个服务器端和一个客户端.

netty的Udp单播、组播、广播实例+Java的Udp单播、组播、广播实例

网络上缺乏netty的udp的单播.组播案例,经过一番学习总结之后终于把这两个案例调通,下面把这两个案例的代码放在这里分享一下. 首先推荐博文: http://colobu.com/2014/10/21/udp-and-unicast-multicast-broadcast-anycast/#Netty%E4%B8%8E%E5%8D%95%E6%92%AD%EF%BC%8C%E7%BB%84%E6%92%AD netty的Udp单播.组播.广播实例+Java的Udp单播.组播.广播实例, 这些代

[java]基于UDP的Socket通信Demo

java课编程作业:在老师给的demo的基础上实现客户端发送数据到服务器端,服务器端接受客户端后进行数据广播. 整体功能类似于聊天室,代码部分不是太难,但是在本机测试的时候出现这样的问题: 服务端通过将每一个Socket客户端的IP存入Set集合,每次接受到数据后都向当前所有的IP转发.但是本机演示的时候所有开的ChatClient客户端都是同一IP,怎么测试呢? 解决办法就是本机测试时候服务端向多个不同的端口转发就好了,这样跑起来的客户端是在不同端口上进行监听的(只是为了实现广播,实际应用下还

java使用UDP协议传输数据

UDP协议(User Datagram Protocol,用户数据报协议)不同于TCP协议,它是不可能靠的,但是它比TCP协议具有更快的传输速度,UDP发送的数据单元称为数据报,当网络传输UDP传输UDP数据报是无法保证数据能够到达目的地,也无法保证按发送的顺序到达目的地,也就是说先发送了"hello",再发送了"world",但接收方可能会先收到"world",再收到"hello",也有可能收不到数据,为什么呢?因为它是不可

[Java] Tcp/udp 简单通信

本文转自  我自己的博客guozeyiblog.cn 欢迎来访 效果图: //UDP通信 import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.*; import javax.swing.*; class send extends JFrame implements ActionL