Java Network Programming (2) InetAddress class and udp protocol, inetaddressudp

Source: Internet
Author: User
Tags time in milliseconds fully qualified domain name

Java Network Programming (2) InetAddress class and udp protocol, inetaddressudp
InetAddress class

JDK provides the java.net package for developing network applications. The classes and interfaces under this package are almost all network programming services.

InetAddress: the object used to describe the IP address

The InetAddress class does not provide a constructor,

Instead, a static method is provided to obtain the InetAddress instance.

Three methods to obtain the IP address and Host Name of the InetAddress instance

 

Package net. csdn. web; import java. io. IOException; import java.net. inetAddress; public class Demo1 {/*** @ param args * @ throws IOException */public static void main (String [] args) throws IOException {// obtain the InetAddress instance InetAddress ia = InetAddress Based on the host name. getByName ("192.168.49.50"); // determines whether the System is accessible. out. println ("whether oneedu can be reached" + ia. isReachable (2000); // obtain the InetAddress instance's IP string System. out. println (ia. getHostAddress (); // obtain the Host Name of the InetAddress instance's IP string System. out. println (ia. getHostName (); // obtain the Fully Qualified Domain Name System for the IP address of the InetAddress instance. out. println (ia. getCanonicalHostName (); // obtain the InetAddress array of the InetAddress instance based on the host name. getAllByName ("www.baidu.com"); // traverses the array for (InetAddress I: ip) {System. out. println (I. getHostAddress () + I. getHostName ());}}}


The output result is as follows:


UDP What is UDP?

The User Data Protocol (UDP) is a User data packet, which is used to process data packets in the same way as the TCP Protocol in the network. In the OSI model, the fourth layer is the transport layer, which is the top layer of the IP protocol.

UDP is a connectionless protocol. Each datagram is an independent information, including the complete source or destination address. It is transmitted to the destination in any possible path on the network, therefore, whether or not to reach the destination, the time to arrive at the destination, and the correctness of the content cannot be guaranteed.

File <64 k


Why UDP?

In an environment with unsatisfactory network quality, UDP packet loss may be serious. However, due to the characteristics of UDP: it is not a connection protocol, so it has the advantages of low resource consumption and high processing speed. Therefore, most of the audio, video, and common data are transmitted using UDP, because even if one or two packets are occasionally lost, they do not have much impact on the received results. For example, ICQ and OICQ used for chatting are UDP protocols.


Manipulating UDP in Java

You can use the initramsocket and initrampacket classes under the Java.net package in JDK to conveniently control user data packets.


DatagramSocket class: Creates a Socket instance for receiving and sending UDP packets.

DatagramSocket (): creates an instance. It is usually used for client programming. It does not have a specific listening port and only uses a temporary one.

DatagramSocket (int port): creates an instance and regularly monitors the Port packets.

DatagramSocket (int port, InetAddresslocalAddr): This is a very useful builder. When a machine has more than one IP address, the instance it creates only receives packets from LocalAddr.

Note: When creating an initramsocket instance, if the port has been used, a SocketException will be generated and thrown, leading to illegal program termination. capture this exception.

Receive (DatagramPacket d): receives data packets to 'd. The receive method generates a "blocking ".

"Blocking" is a specialized term that produces an internal loop that pauses the program in this place until a condition is triggered.

Send (DatagramPacket d): send the message d to the destination.

SetSoTimeout (int timeout): Set the timeout time in milliseconds.

Close (): close DatagramSocket. When an application exits, resources are usually automatically released and the Socket is closed. However, resources cannot be recycled due to abnormal exit. Therefore, when the program is completed, you should take the initiative to use this method to close the Socket, or close the Socket after an exception is caught.


DatagramPacket: used to process packets. It packs data such as the byte array, target address, and target port into packets or disassembles the packets into byte arrays.

DatagramPacket (byte [] buf, int length, InetAddress addr, int port): Extracts long length data from the buf array to create a data packet object. The target is the addr address and port.

DatagramPacket (byte [] buf, int offset, intlength, InetAddress address, int port): extracts data packet objects with long length starting with offset from the buf array, the target is the addr address and port.

DatagramPacket (byte [] buf, int offset, intlength): Pack data starting from offset and long length into the buf array.

DatagramPacket (byte [] buf, int length): load the data with length in the data packet into the buf array.

GetData (): it obtains the byte array encoding of packets from the instance.



Example 1: write a program to show how to send and accept UDP datagram.

Sender

Package net. csdn. web; import java. io. IOException; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; public class DemoSend {public static void main (String [] args) throws IOException {// 1. create a udpsocket service endpoint. This endpoint is created and the system will randomly allocate a port. If you do not want to configure it randomly, You can manually specify it. DatagramSocket ds = new DatagramSocket (); // 2. To encapsulate data in a packet package, you must specify the destination address and port. Byte [] buf = "wo shi shu ju ". getBytes (); InetAddress is = InetAddress. getByName ("192.168.49.50"); DatagramPacket dp = new DatagramPacket (buf, buf. length, is, 9009); // 3. use the send method of the socket service to send the package. Ds. send (dp); // 4. Disable the socket service. It is mainly to close resources. Ds. close ();}}

Acceptor

Package net. csdn. web; import java. io. IOException; import java.net. datagramPacket; import java.net. extends ramsocket; public class DemoReceive {public static void main (String [] args) throws IOException {// 1. create a udp socket service. Listen to a port. DatagramSocket ds = new DatagramSocket (9009); // 2. Define a buffer and encapsulate the buffer into a packet package. Byte [] buf = new byte [1024]; DatagramPacket dp = new DatagramPacket (buf, buf. length); // 3. Store data into data packets through the receive method of socket. Ds. receive (dp); // 4. Obtain the specified information in the package through the methods of data packet dp, such as getData (), getAddress (), and getPort. String ip = dp. getAddress (). getHostAddress (); String data = new String (dp. getData (), 0, dp. getLength (); int port = dp. getPort (); System. out. println (ip + ":" + data + ":" + port); // 5. disable socket. Ds. close ();}}


Open in the cmd command window:

 


Example 2: write a program to demonstrate how to send and accept UDP-based datagram. You can enter the data on the keyboard.

Sender

package net.csdn.web;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class DemoSend2 {/** * @param args */public static void main(String[] args) throws IOException {// TODO Auto-generated method stubDatagramSocket ds = new DatagramSocket();BufferedReader br = new BufferedReader(new InputStreamReader(System.in));String line = null;while((line = br.readLine()) != null){if(line.equals(888)){break;}byte[] buf = line.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.49.255"),9009);ds.send(dp);}ds.close();}}


Acceptor

package net.csdn.web;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;public class DemoReceive2 {public static void main(String[] args) throws IOException {// TODO Auto-generated method stubDatagramSocket ds = new DatagramSocket(9009);while(true){byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);ds.receive(dp);String ip = dp.getAddress().getHostAddress();String data = new String(dp.getData(),0,dp.getLength());System.out.println(ip+":"+data);}}}



 

Dialog box for sending and receiving in the same region

package src.com.hbsi.net;import java.net.*;import java.io.*;public class ChatDemo {/** * @param args */public static void main(String[] args) {try {DatagramSocket send=new DatagramSocket();DatagramSocket rece=new DatagramSocket(9008);new Thread(new ChatSend(send)).start();new Thread(new ChatRece(rece)).start();} catch (SocketException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}class ChatSend implements Runnable{    DatagramSocket ds;        public ChatSend(DatagramSocket ds){    this.ds=ds;    }    @Overridepublic void run() {try{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String line=null;while((line=br.readLine())!=null){if(line.equals("over"))break;byte[] buf=line.getBytes();DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.49.255"),9008);ds.send(dp);}ds.close();}catch(Exception e){e.printStackTrace();}}}class ChatRece implements Runnable{ DatagramSocket ds;     public ChatRece(DatagramSocket ds){    this.ds=ds;   }@Overridepublic void run() {while(true){try{byte[] buf=new byte[1024];DatagramPacket dp=new DatagramPacket(buf,buf.length);ds.receive(dp);String ip=dp.getAddress().getHostAddress();String data=new String(dp.getData(),0,dp.getLength());System.out.println(ip+":"+data);}catch(Exception e){e.printStackTrace();}}}}



Reprinted please mark the address http://blog.csdn.net/zhaoyazhi2129/article/details/40422301


For java Network Programming, what are the key classes to use when using TCP for network programming? What are the key classes to use for UDP?

TCP: Socket, ServerSocket, ServerSocketChannel, SocketChannel
UDP: DatagramSocket, DatagramPacket

Java Network Programming UDP Network Programming Problems

New InputStreamReader (System. in ));

Have you entered something on the sender?
System. out. println ("-- From Address:" + dgp. getAddress () + ": -- IP:" + dgp. getPort () + "message --");

Have you printed this sentence? We recommend that you follow the code in debug.

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.