Java Learning Summary (13)--network programming based on UDP protocol

Source: Internet
Author: User
Tags thread class

A UDP Network Programming
1. For non-connected data transmission, unreliable, but high efficiency (audio, video, etc.).
2.UDP data sent at once cannot exceed 64kb.
Classes required for 3.UDP programming
(1) Datagramsocket This class represents the socket used to send and receive datagram packets
(2) Datagrampacket This class represents a datagram packet
Method: Datagrampacket (Byte[]?buf, Int?length, inetaddress?address, Int?port)
Parameter representation: BUF-Packet data
Length-Package Lengths
Address-Destination
Port-Destination Ports
4.DatagramSocket Common methods
(1) Construction Method: public datagramsocket (int port)
(2) Common methods: #public void Send (Datagrampacket p)
#public void Receive (Datagrampacket p)
5.DatagramPacket Common methods
(1) Construction Method: Public Datagrampacket (byte[] buf,int length) This construction method is used to receive
Data
(2) public? Datagrampacket (Byte[]?buf, int?length, inetaddress address, Int?port) This construction method is used to assemble the data that will be sent
(3) Public inetaddress getaddress (): Returns IP that will send the IGN's IP or received data
(4) Public byte[] GetData (): Returns the data buffer that will be sent or the data buffer that has been received
(5) public int getlength (): Returns the length of data to be sent or the length of data received
6. Network programming based on TCP and UDP Protocol (difference):
(1) Socket programming based on TCP protocol: #. Communication needs to establish a connection; #. The two sides have the primary and secondary points when the connection is established
(2) Socket programming based on UDP protocol: #. Communication double-hair does not need to establish a connection; #. Complete equality between the two sides of the communication
7. Socket programming based on UDP protocol
(1) UDP Socket Communication model:

Example (UDP sample):
Message Send Thread class:
Package UDP;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
Send Thread class
public class Sendrunnable implements runnable{
Private String Desthost;
private int port;
Private Datagramsocket DS;

public SendRunnable(String destHost, int port, DatagramSocket ds) {    this.destHost = destHost;    this.port = port;    this.ds = ds;}@Overridepublic void run() {    while(true){        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));        System.out.print(Thread.currentThread().getName()+":");        String say;        DatagramPacket dp=null;        try {            say=br.readLine();            dp=new DatagramPacket(say.getBytes(),say.getBytes().length ,InetAddress.getByName(destHost), port);            ds.send(dp);         } catch (IOException e) {            e.printStackTrace();        }    }}

}

Information Receive thread class:
Package UDP;

Import java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
/ Receive thread class
/
public class Receiverunnable implements Runnable {
Private Datagramsocket DS;

public ReceiveRunnable(DatagramSocket ds) {    this.ds = ds;}@Overridepublic void run() {    while (true) {        byte[] b = new byte[1024];        DatagramPacket dp = new DatagramPacket(b, b.length);        try {            ds.receive(dp);// 接收之前一直阻塞            String ip = dp.getAddress().getHostName();// 获取发送方的IP            int post = dp.getPort();// 获取发送方的端口号            System.out.println(ip + ":" + post + "说:"                    + new String(dp.getData(), 0, dp.getLength()));        } catch (IOException e) {            e.printStackTrace();        }    }}

}

Chat Port One:
Package UDP;

Import Java.net.DatagramSocket;
Import java.net.SocketException;
Class Chat1 {

public static void main(String[] args) throws SocketException {    DatagramSocket ds=new DatagramSocket(9999);    new Thread(new ReceiveRunnable(ds)).start();    new Thread(new SendRunnable("localhost", 8888, ds),"白雪公主").start();}

}

Chat Port two:
Package UDP;

Import Java.net.DatagramSocket;
Import java.net.SocketException;

public class Chat2 {

public static void main(String[] args) throws SocketException {    DatagramSocket ds=new DatagramSocket(8888);    new Thread(new ReceiveRunnable(ds)).start();    new Thread(new SendRunnable("localhost", 9999, ds),"青蛙王子").start();}

}

Run results
Snow White: 127.0.0.1:8888 said: Hello, Princess.
Hello, Prince.
Snow White: 127.0.0.1:8888 said: What are you doing, princess?
I was chatting with you.
Princess Snow White:

Prince Frog: Hello, Princess.
Frog Prince: 127.0.0.1:9999 said: Hello, Prince.
What are you doing, princess?
Frog Prince: 127.0.0.1:9999 said: I am chatting with you

Java Learning Summary (13)--network programming based on UDP protocol

Related Article

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.