Research on the programming of UDP protocol based on Java

Source: Internet
Author: User
Tags final socket

It is relatively easy to do network programming in Java, because the java.net package in J2SE is well encapsulated in various communication protocols, this article mainly describes how to write applications based on UDP (User datagram) protocol.

Usually we do network programming is generally using socket based TCP/IP programming, after all, TCP/IP applications are very extensive, such as we browse the Internet is based on the HTTP protocol, we send mail through the SMTP protocol. They are all based on TCP/IP. The most important thing about TCP/IP transmission is that it can ensure that the data arrives at the destination, but UDP is different. He does not guarantee accurate transmission and the data is likely to be lost. If you are interested, the reader can refer to the book "Computer Network".

Before introducing UDP programming it is necessary to introduce an important class inetaddress, in the simplest words to describe the role of this class is: it represents an IP address. This is very important. If you know the IP address in the Internet, it means we know the end of the communication. This class does not have a constructor but there are several factory methods to get a inetaddress instance by passing different parameters such as Ip,hostname, the following small example can get the IP address of my machine.

import java.net.*;
public class TestNet
{
 public static void main(String[] args) throws Exception
 {
  InetAddress ia = InetAddress.getByName("compaq");
  String ipAdr = ia.getHostAddress();
  System.out.println(ipAdr);
 }
}

Of course, the name of my machine is Compaq, if you pass the localhost, you will get 127.0.0.1.

It's easy to understand how to use UDP programming, so we should first construct a datagram and then send it out, and we can also receive datagrams. The Datagrampacket and Datagramsocket two classes are provided in Java to complete such a task, which is responsible for constructing the datagram, which is responsible for sending and receiving. Look at the Datagrampacket builder.

DatagramPacket(byte[] buf, int length, InetAddress address, int port)
DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
DatagramPacket(byte[] buf, int offset, int length, SocketAddress address)
DatagramPacket(byte[] buf, int length, SocketAddress address)
DatagramPacket(byte[] buf, int length)
DatagramPacket(byte[] buf, int offset, int length)

The first four of these are used for structuring datagrams sent because they have inetaddress or socketinetaddress as the address of the receiving endpoint, and the latter one is for the datagram.

We also write an example of C/S model to illustrate how to use these two important classes, if not familiar with the API please refer to Java Doc. The following procedures create a time server in this organization, the client to obtain time. A similar time server program has been written before, but this is based on UDP programming.

Import java.io.*
Import java.net.*
Import java.util.*
public class Timeserver {
Final private static int daytime_port = 13;
public static void Main (String args[]) throws
IOException {
Datagramsocket socket = new Datagramsocket ( Daytime_port);     
while (true) {
byte buffer[] = new byte[256];
Datagrampacket packet =new datagrampacket (buffer, buffer.length);
Socket.receive (packet);
String date = new Date (). ToString ();
buffer = date.getbytes ();
//Get response Address/port
//To client from packet
InetAddress address = packet.getaddress ();
int port = Packet.getport ();
Packet = new Datagrampacket (buffer, buffer.length, address, Port);
Socket.send (packet);
}
}
}
Import java.io.*
Import java.net.*
public class GetTime {
Final private static I NT Daytime_port = 13;
public static void Main (String args[]) throws
IOException {
if (args.length = = 0) {
System.err.println ("Please specify daytime host");
System.exit (-1);   
}
String host = args[0];
byte message[] = new byte[256];
InetAddress address = inetaddress.getbyname (host);
System.out.println ("Checking at:" + address);   
Datagrampacket packet = new Datagrampacket (message, message.length,
Address, daytime_port);
Datagramsocket socket = new Datagramsocket ();
Socket.send (packet);
Packet =new datagrampacket (message, message.length);
Socket.receive (packet);
String time = new String (Packet.getdata ());
System.out.println (The time at "+ Host +" are: "+ time);
Socket.close ();
}
}

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.