DatagramSockets是Java通过UDP而不是TCP进行网络通信的机制。Java提供了DatagramSocket来通过UDP而不是TCP进行通信。它也建立在IP之上。DatagramSockets可用于通过互联网发送和接收数据包。
UDP优于TCP的一个例子是电视频道的直播。在这方面,我们希望将尽可能多的帧传输给现场观众,而不必担心丢失一两帧。TCP作为一种可靠的协议,在传输过程中增加了自身的开销。 另一个首选UDP的例子是在线多人游戏。在像《反击战》或《使命召唤》这样的游戏中,除了最重要的信息外,没有必要传递所有信息。还应该注意的是,现实生活中的大多数应用程序都谨慎地混合使用UDP和TCP;通过TCP传输关键数据,并通过UDP传输其余数据。
本文是单边客户机-服务器程序的一个简单实现,其中客户机向服务器发送消息,服务器只打印消息,直到客户机发送“再见”。
Java数据报编程模型步骤
- 创建DatagramSocket:- 首先,创建datagramSocket对象,将数据包传送到目的地,并在服务器发送任何数据时接收数据包。要创建datagramSocket,可以使用以下构造函数:
- 受保护的DatagramSocket DatagramSocket():
Syntax: public DatagramSocket() throws SocketException Creates a datagramSocket and binds it to any available port on local machine. If this constructor is used, the OS would assign any port to this socket.
- 受保护的DatagramSocket DatagramSocket(int端口):-
Syntax: public DatagramSocket(int port) throws SocketException Parameters: port - port to which socket is to be bound Throws: SocketException - If the socket cannot be bound to the specific local port. Creates a DatagramSocket and binds to the specified port on the local machine.
- 受保护的DatagramSocket DatagramSocket(int端口,InetAddress InetAddress):-
Syntax: public DatagramSocket(int port, InetAddress inetaddress) throws SocketException Parameters: port - port to which socket is to be bound. inetaddress - local address to which socket is to be bound. Throws: SocketException - If the socket cannot be bound to the specific local port. It creates a DatagramSocket and binds it to specified port and ip-address.
- 受保护的DatagramSocket DatagramSocket():
- 创建数据包: 在该步骤中,创建用于经由datagramSocket发送/接收数据的分组。
- 要发送数据的构造函数: DatagramPacket(字节buf[],int长度,InetAddress,InetAddress,int端口):-
Syntax: public DatagramPacket(byte[] buf, int offset, int length, SocketAddress address) Parameters: buf - the packet data. offset - the packet data offset. length - the packet data length. address - the destination socket address. Constructs a DatagramPacket for sending data at specified address and specified port.
- 用于接收数据的构造函数: DatagramPacket(字节buf[],整数长度):-
Syntax: public DatagramPacket(byte buf[], int length) Parameters: buf - the packet data. length - the packet data length. Constructs a DatagramPacket for receiving the data of length length in the byte array buf.
- 要发送数据的构造函数: DatagramPacket(字节buf[],int长度,InetAddress,InetAddress,int端口):-
- 对套接字对象调用send()或receive()调用
Syntax: void send(DatagramPacket packet) throws SocketException Parameters: packet - Datagrampacket to send. Throws: SocketException - If there is an error in binding. IllegalArgumentException - if address is not supported by the socket.
Syntax: void receive(DatagramPacket packet) throws SocketException Parameters: packet - Datagrampacket to receive from this socket. Throws: SocketException - If there is an error in binding. IllegalArgumentException - if address is not supported by the socket.
客户端实现
JAVA
// Java program to illustrate Client side // Implementation using DatagramSocket import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class udpBaseClient_2 { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); // Step 1:Create the socket object for // carrying the data. DatagramSocket ds = new DatagramSocket(); InetAddress ip = InetAddress.getLocalHost(); byte buf[] = null ; // loop while user not enters "bye" while ( true ) { String inp = sc.nextLine(); // convert the String input into the byte array. buf = inp.getBytes(); // Step 2 : Create the datagramPacket for sending // the data. DatagramPacket DpSend = new DatagramPacket(buf, buf.length, ip, 1234 ); // Step 3 : invoke the send call to actually send // the data. ds.send(DpSend); // break the loop if user enters "bye" if (inp.equals( "bye" )) break ; } } } |
输出:
Hello I am Client. ... bye
服务器端实现
JAVA
// Java program to illustrate Server side // Implementation using DatagramSocket import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class udpBaseServer_2 { public static void main(String[] args) throws IOException { // Step 1 : Create a socket to listen at port 1234 DatagramSocket ds = new DatagramSocket( 1234 ); byte [] receive = new byte [ 65535 ]; DatagramPacket DpReceive = null ; while ( true ) { // Step 2 : create a DatgramPacket to receive the data. DpReceive = new DatagramPacket(receive, receive.length); // Step 3 : revieve the data in byte buffer. ds.receive(DpReceive); System.out.println( "Client:-" + data(receive)); // Exit the server if the client sends "bye" if (data(receive).toString().equals( "bye" )) { System.out.println( "Client sent bye.....EXITING" ); break ; } // Clear the buffer after every message. receive = new byte [ 65535 ]; } } // A utility method to convert the byte array // data into a string representation. public static StringBuilder data( byte [] a) { if (a == null ) return null ; StringBuilder ret = new StringBuilder(); int i = 0 ; while (a[i] != 0 ) { ret.append(( char ) a[i]); i++; } return ret; } } |
简而言之,我们可以将通过UDP发送和接收数据的步骤总结如下:-
- 对于通过UDP发送数据包,我们应该知道4件事, 要发送的消息、其长度、目的地的IP地址、目的地正在侦听的端口。
- 一旦我们知道了所有这些,我们就可以创建套接字对象来承载数据包和实际拥有数据的数据包。
- 调用send()/receive()调用以实际发送/接收数据包。
- 从接收到的数据包中提取数据。
输出:
Client:- Hello Client:- I am client. ... Client:- bye Client sent bye.....EXITING
注意:-为了在系统上测试上述程序,请确保先运行服务器程序,然后运行客户端程序。确保您在客户端控制台中,并从那里继续键入消息,每个消息后面都有回车符。每次发送消息时,都会根据您的环境设置重定向到服务器控制台。如果没有自动重定向,请切换到服务器控制台以确保收到所有消息。最后,要终止通信,请键入“bye”(不带引号)并按enter键。
作为一个热情的读者,你也应该尝试并实现一个双向聊天应用程序,在这个应用程序中,服务器将能够在他喜欢的时候响应消息。
参考资料: http://download.java.net/jdk7/archive/b123/docs/api/java/net/DatagramSocket.html http://download.java.net/jdk7/archive/b123/docs/api/java/net/DatagramPacket.html
本文由 Rishabh Mahrsee .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。