UDP Programming for Java

Source: Internet
Author: User

Plain English: Each computer has its own IP address, sends data to the specified IP address, and the data is sent to the specified computer. UDP communication is only a means of communication, its characteristics are not much to say. With the IP address data can be sent to the designated computer, but it! I send the data to the computer, which program in the computer receives it. Do not know the parents know, in fact, every network software has its own communication port, such as QQ, cool dog music download port and so on. Now you know, to send the data to the specified IP address and the specified port before it can be sent to the specified program (our own program, of course).

We have to do two programs to send and receive the end of the first to do the sending side

Java provides a class datagramsocket specifically for UDP communication;DatagramSocket(int port)的构造方法---可以设定该程序通信的的端口(就像上面说的有ip了还需要端口,这是设定该程序的通信端口);该类提供了发送数据包的方法send(DatagramPacket p),接收数据包的方法receive(DatagramPacket p)

Then Datagramsocket senddatagramsocket = new Datagramsocket (10000);

Senddatagramsocket. Send (Datagrampacket p); These two sentences are finished, the first sentence sets the communication port of the sender, the second sentence, sends the data

Just a little bit to send to where!! Look down.

为什么叫数据包呢!上面不是说了,要想通信成功必须向指定的ip地址和指定的端口发数据,发送的时候数据被打包了,里面包含了要发送到的ip地址,端口,和想发的数据(被打包了),注意send(DatagramPacket p)里面的DatagramPacket p,你查一下java的中文api帮助文档就会知道DatagramPacket是一个类,他有一个构造方法DatagramPacket(byte[] buf, int length, InetAddress address, int port) 文档中的解释----构造数据报包,用来将长度为 length 的包发送到指定主机(指定ip地址)上的指定端口号;第一个参数byte[] buf发送的数据,类型为byte[],第二个参数int length,发送数据的长度,第三个InetAddress address发送的ip地址,类型为InetAddress ,第四个端口号。

好那么我先写一个数据String string = "yangfengwu";然后转化一下byte[] by = string.getBytes();意思是转化成字符数组

相当于byte[] by ={‘y‘,‘a‘,‘n‘,‘g‘,‘f‘,‘e‘,‘n‘,‘g‘,‘w‘,‘u‘};不要嫌麻烦,这样写好处大大的有,如果做界面开发,文本框中我们所传的数据都是字符串类型的!!

好接着DatagramPacket sendPscket = new DatagramPacket(by, by.length,InetAddress.getByName("192.168.32.1"),8080);

好说一下这个InetAddress.getByName("192.168.32.1")。InetAddress是一个java中的类,他就是专门操作ip的,列如

InetAddress i = Inetaddress.getlocalhost ();

System.out.println (i.ToString ()); These two sentences can print out the name and IP address of the machine.

We usegetByName(String host)该方法的作用----在给定主机名的情况下确定主机的 IP 地址。

The hostname can be a machine name (such as " java.sun.com ") or a textual representation of its IP address . If you provide a literal IP address, only the validity of the address format is checked.

InetAddress ip = InetAddress.getByName("192.168.32.1");

DatagramPacket sendPscket = new DatagramPacket(by, by.length, ip ,8080);
sendDatagramSocket .send(DatagramPacket p);     发送  sendDatagramSocket .send(sendPscket );

The following is the complete send-side program

Package server;

Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;

public class Server_test {
public static void Main (string[] str)
{
Try
{
Creates a Datagramsocket object and specifies that the program's communication port is 10000
Datagramsocket senddatagramsocket = new Datagramsocket (10000);
Determine the message to send
String string = "Yangfengwu";
Convert to character array type
byte[] by = String.getbytes ();
Determine the address to send
inetaddress IP = inetaddress.getlocalhost ();//If it is your own computer test can get the native address, you can also check their own IP address

inetaddress IP = inetaddress.getbyname ("192.168.32.1");

Determine the port to send
int port = 8080;
Create a Send-type packet that contains the IP address and port to which it is destined
Datagrampacket sendpscket = new Datagrampacket (by, By.length,inetaddress.getbyname ("192.168.32.1"), port);
Sending data via the Datagramsocket send method
Senddatagramsocket.send (Sendpscket);
Create a Receive Buffer
byte[] bt = new byte[1024];
Create a packet of the receive type

//DatagramPacket(byte[] buf, int length)Constructed to DatagramPacket receive packets of length length

Datagrampacket receivepacket = new Datagrampacket (BT, bt.length);
Sending data through the Datagramsocket receive method
Senddatagramsocket.receive (Receivepacket);
Print---Packets
String dastring = new
string (Receivepacket.getdata (), 0,receivepacket.getlength ());//GetData () Method is to return the data buffer
System.out.println (dastring);
Close Receive
Senddatagramsocket.close ();
}
catch (Exception e)
{
TODO auto-generated Catch block
E.printstacktrace ();
}

}
}

The following is the complete receive-side program

Package client;

Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;

public class Client_test {
public static void Main (string[] str)
{
Try
{
Determine port
int port = 8080;
Creates a Datagramsocket object and specifies that the program's communication port is 8080
Datagramsocket receivesocket = new Datagramsocket (port);
while (true)
{
Create a Receive Buffer
Byte[] by = new byte[1024];
Create a Receive packet
Datagrampacket receivepacket = new Datagrampacket (by, by.length);
Receive data
Receivesocket.receive (Receivepacket);
Parsing messages and printing data
String string =new string (Receivepacket.getdata (), 0,receivepacket.getlength ());
System.out.println (string);
The packet can also resolve IP, and port, print
InetAddress ipAddress = receivepacket.getaddress ();
int receiveport = Receivepacket.getport ();
System.out.println (ipAddress);
System.out.println (ReceivePort);
Send data
String aastring = "123";
byte[] bb = aastring.getbytes ();
Create a packet of the sending type
Datagrampacket sendpscket = new Datagrampacket (BB, Bb.length,inetaddress.getbyname ("192.168.32.1"), 10000);
Receivesocket.send (Sendpscket);
}

Receivesocket.close ();
}
catch (Exception e)
{
TODO auto-generated Catch block
E.printstacktrace ();
}

}
}

UDP Programming for Java

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.