UDP interpretation of Java network programming

Source: Internet
Author: User

On the client code first

Package Com.test.net;import Java.net.datagrampacket;import Java.net.datagramsocket;import java.net.InetAddress; public class UdpClient {/** *udp client */public static void main (string[] args) throws Exception {Datagramsocket socket=new D Atagramsocket (); String str= "Hello"; byte[] Buf=str.getbytes ();D atagrampacket packet=new datagrampacket (Buf,buf.length, Inetaddress.getbyname ("127.0.0.1"), 1111);/* Direct Contract */socket.send (packet);}}

Server-side code

Package Com.test.net;import Java.net.datagrampacket;import Java.net.datagramsocket;import java.net.InetAddress; Import Java.net.socketexception;public class Udpserver {/** *udp server */public static void main (string[] args) throws Except Ion {Datagramsocket socket=new datagramsocket (1111); byte[] Buf=new byte[256];D atagrampacket packet=new DatagramPacket (buf,buf.length);/* monitor, Block */socket.receive (packet); String Received=new string (Packet.getdata ()); System.out.println (Received);}}

First here to explain the UDP,UDP protocol is a non-connection protocol, simply speaking, is one-way send, do not need to establish a connection in advance, do not need to return the package. Therefore, only need an IP and port, UDP can be sent to this port, as to whether the IP and port, or the recipient does not receive, UDP is no matter. So the most important thing in UDP is two classes, one is Datagramsocket, the other is Datagrampacket, the first one is similar to socket, the second is UDP packet.

In the server, the receive method of the Datagrampacket is blocked, which is the equivalent of listening until the datagram is heard.

Output results



The result is that the server side outputs hello.

UDP interpretation of Java network programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.