原文: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).

 

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

  1. java之UDP(datagramsocket,datagramPacket)实例

    import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import ...

  2. Java实现UDP之Echo客户端和服务端

    Java实现UDP之Echo客户端和服务端 代码内容 采用UDP协议编写服务器端代码(端口任意) 编写客户机的代码访问该端口 客户机按行输入 服务器将收到的字符流和接收到的时间输出在服务器consol ...

  3. Java TCP/UDP网络通信编程

    本文转自:http://www.cnblogs.com/cdtarena/archive/2013/04/10/3012282.html 网络应用中基本上都是TCP(Transmission Cont ...

  4. (Java学习笔记) Java Networking (Java 网络)

    Java Networking (Java 网络) 1. 网络通信协议 Network Communication Protocols Network Protocol is a set of rul ...

  5. Java使用UDP发送数据到InfluxDB

    最近在做压测引擎相关的开发,需要将聚合数据发送到InfluxDB保存以便实时分析和控制QPS. 下面介绍对InfluxDB的使用. 什么是InfluxDB InfluxDB是一款用Go语言编写的开源分 ...

  6. Java Socket UDP编程

    package com; import java.io.IOException; import java.net.*; /** * UDP Client * * Created by Administ ...

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

    网络上缺乏netty的udp的单播.组播案例,经过一番学习总结之后终于把这两个案例调通,下面把这两个案例的代码放在这里分享一下. 首先推荐博文: http://colobu.com/2014/10/2 ...

  8. PL/SQL 调用JAVA使用UDP发送数据

    步骤如下 1.直接在SQL命令中写入JAVA代码(用SYS帐号执行,不然权限等太麻烦) create or replace and resolve java source named udp as i ...

  9. Java垃圾回收手册翻译 - 什么是垃圾回收

    Java垃圾回收手册翻译 - 什么是垃圾回收 初看之下,垃圾回收应该要做其名称之事 - 找到和丢掉垃圾.然而事实上它正好做着相反的事,垃圾回收会记录所有仍在使用中的对象,然后将其他标记为垃圾.谨记这点 ...

随机推荐

  1. 在POM配置Maven plugin提示错误“Plugin execution not covered by lifecycle configuration”的解决方案

    eclipse在其POM文件的一处提示出错如下: Plugin execution not covered by lifecycle configuration: org.apache.maven.p ...

  2. thymeleaf(一)

    (一)Thymeleaf 是个什么?      简单说, Thymeleaf 是一个跟 Velocity.FreeMarker 类似的模板引擎,它可以完全替代 JSP .相较与其他的模板引擎,它有如下 ...

  3. eclipse测试链接sql server2008 数据库

    注:在测试连接数据库之前必须保证SQL Server 2008是采用SQL Server身份验证方式而不是windows身份验证方式.如果在安装时选用了后者,则需要重新进行配置. 首先 使用命令行测试 ...

  4. linux命令sync,shutdown

    1.数据同步写入磁盘: sync 输入sync,那举在内存中尚未被更新的数据,就会被写入硬盘中 hling@hling:~$ sync   2.惯用的关机指令:shutdown 实例:

  5. Python学习之旅(二十六)

    Python基础知识(25):常用内建模块 1.datetime:处理日期和时间 (1)获取当前日期和时间 from datetime import datetime now = datetime.n ...

  6. intput/output 文件的复制练习

    import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStrea ...

  7. 实战一个职业技术学校。 by:hack某某

    这是我们的目标,某一技术学院,这是一个注入点 上sqlmap 跑出了管理账号密码 扫后台 没有找到,注入就相当鸡肋了 换换其他思路 dba权限,想到了直接写入 找找路径之类的 找到了,运气相当的好 直 ...

  8. 部署WEB项目到服务器(三)安装mysql到linux服务器(Ubuntu)详解

    突发奇想,想在自己电脑上部署一个web网站. 1,首先是下载一个适合自己已安装服务器版本的mysql数据库. 这里使用网上的链接http://dev.mysql.com/downloads/mysql ...

  9. HTML轮播图实现(前后端分离)

    1,首先前后端分离用到了3个插件 2,异步请求后端获取数据库图片地址(图片名字) //图片轮播 axios({ url:'http://127.0.0.1:8000/userctrl/image', ...

  10. 外星人入侵——安装Pygame

    本文以win10和Python3为例来介绍如何安装Pygame. 安装Pygame需要使用pip,我们首先检查pip是否已被安装. 打开一个终端窗口,并执行如下命令 C:\Users\hys>p ...