UDP network Programming (i) __ programming

Source: Internet
Author: User
UDP Network Programming

Network communication based on TCP protocol can establish reliable connection, and also consume a lot of system performance, in order to reduce system overhead, UDP transmission protocol is provided in network communication. UDP is an unreliable connection and is widely used in chat tools.

Using the UDP protocol to send data, all information is sent as datagrams, but the client is not necessarily able to accept success. UDP network traffic is implemented in Java using the Datagramsocket class and the Datagrampacket class. One: Datagramsocket

Datagramsocket class
Method type Description
Public Datagramsocket () Construction method Constructing the Datagramsocket object does not specify a listening port

Public datagramsocket (int prot)

Construction method Constructs the Datagramsocket object to specify the listening port
public void Send (Datagrampacket p) Construction method Send Datagrams
public void receive (Datagrampacket p) Method Accept Datagram

Use the Datagramsocket class to write the sender, and the system automatically assigns a port number if the port number is not specified when constructing the Datagramsocket object. This is equivalent to shop phone, you can use landline, PHS, mobile phone to achieve dial-up. But the other person's phone number is fixed, that is, the receiving program must specify a port number. UDP datagrams are sent and received via datagram sockets, and the system does not guarantee that the UDP datagram will be safely delivered to the destination or when it can be datagramsocket. Two: Datagrampacket

The main methods of the Datagrampacket class
Method Type Describe
Public Datagrampacket (byte[] buf,int length) Construction method Specify memory space and size when constructing Datagrampacket object
Public Datagrampacket (byte[] buf,int length,inetaddress address,int Prot) Construction method Specify memory space and size, destination address, and port when constructing Datagrampacket object
Public byte[] GetData () Method Return receive data
public int GetLength () Method Returns the length of data sent or received
Public inetaddress getaddress () Method Return the address of the machine

The Datagrampacket object encapsulates the UDP datagram, which contains the IP address and port number of the sender and the IP address and port number of the receiver at the end of the datagram. Each datagram in the UDP protocol gives full address information, so there is no need to establish a connection between the sender and the receiver. Three: InetAddress class

InetAddress Main methods
Method type Description
public static inetaddressgetbyname (String host) Method Get a inetaddtess by host name or IP address
public static String GetHostName () Method Gets the host name of the IP address
Public String gethostaddress () Method return IP address string

The

 inetaddress class is used to represent computer addresses. UDP Communication Flow process: 1. Datagramsocket and Datagrampacket 2. Set up the sending and receiving terminals 3. Set up Packet 4. Call the socket send, Receive method 5. Turn off the socket write UDP network program needs to write the sending program and receive the program separately. They are two separate running programs.   Example One: note: First open the receiver end. (Don't say much)

/**
	 * Send program
	 * @throws ioexception
	/@org. junit.test public
	Void Send () throws ioexception{
		// Create a datagram
		datagramsocket ds=new datagramsocket ();
		byte[] buf= "Hello World". GetBytes ();
		Create a packet, each packet can not be greater than 64k, send data information (BUF) sent to (where). ) IP (127.0.0.1), port number, (9090)
		datagrampacket dp=new datagrampacket (buf, 0, Buf.length, Inetaddress.getbyname (" 127.0.0.1 "), 9090);
		Ds.send (DP);
		Ds.close ();
	}
	
	/**
	 * Receive program
	 * @throws ioexception
	/@org. Junit.test public
	Void Receive () throws IOException {
		datagramsocket ds=new datagramsocket (9090);
		Byte[] Buf=new byte[1024];
		Datagrampacket dp=new datagrampacket (buf, 0, buf.length);
		The data in the datagram is written to the
		Ds.receive (DP) in the DP packet;
		System.out.println (New String (Dp.getdata (), 0,dp.getlength ()));
		Ds.close ();
	}
Print results: Hello World Example Two:
/** * Send program/@org. Junit.test public void Udpsend () {Datagramsocket ds=null;
		Datagrampacket Dp=null;
			The try {//ds is used to complete the sending of the message ds=new datagramsocket ();
			String info= "Hello World"; /** * The message to be sent is packaged as Datagrampacket,datagrampacket specifies the destination host address and port for message relaxation/dp=new Datagrampacket (Info.getbytes (), info.ge
			Tbytes (). Length,inetaddress.getbyname ("localhost"), 3000);
		Ds.send (DP);
		catch (Exception e) {//Todo:handle Exception e.printstacktrace (); }finally{ds.close ()//When the message is sent, close the object}/** * Receiver/@org. Junit.test public void Udpreceive () {DATAGRAMSO
		Cket Ds=null;
		Datagrampacket Dp=null;
		Byte[] Buf=new byte[1024]; When a try {/** * (Dispatcher) sends a message, the specified message sends a target port of 3000, so in the receiving program, the port number should be consistent with the port number specified in the sender's packet when the * Datagramsocket object is built Ds=ne
			W Datagramsocket (3000);//Get 3000-Port datagram dp=new datagrampacket (BUF, 1024);//Create a packet to receive data sent by the sending program.
			Ds.receive (DP)//to write (receive) The datagram information from Port 3000 to the DP packet.
			String Str=new string (Dp.getdata (), 0,dp.getlength ());Str=str+ "from" +dp.getaddress (). gethostaddress ();
			
		System.err.println (str);
		catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
		}finally{Ds.close (); }
	}
The receiving end prints the result: Hello World from 127.0.0.1

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.