Java UDP Network Programming Example-java Learning Notes (30) __ Algorithm

Source: Internet
Author: User

Java UDP network programming is implemented mainly through the Datagramsocket and Datagrampacket two classes, the following is an example program,
The server listens on UDP 2000 ports and prints the received long type values
The client then gets a long value by entering it and sends it to the server

Server:/**//* Coding by NYZHL *
Import java.net. * ;
Import java.io. * ;

public class Datagramserver ... {
public static void Main (string[] args) ... {
Datagramsocket ds = null;
Try ... {
ds = new Datagramsocket (2000);
}
catch (SocketException e) ... {
E.printstacktrace ();
System.exit (-1);
}
byte[] buffer = new byte[1024];
Datagrampacket DP = new Datagrampacket (buffer,buffer.length);
while (true) ... {
DataInputStream in = new DataInputStream (
New Bytearrayinputstream (buffer)
);
Try ... {
Ds.receive (DP);
System.out.println (In.readlong ());
In.close ();
}
catch (IOException e) ... {
E.printstacktrace ();
Continue
}
}
Ds.close (); JDK prompts "statements that cannot be accessed"
Because the front is a dead loop, you can't execute the following statement anyway
}
}

Client:/**//* Coding by NYZHL *
Import java.net. * ;
Import java.io. * ;

public class datagramclient ... {
public static void Main (string[] args) ... {
Datagramsocket ds = null;
Try ... {
ds = new Datagramsocket ();
}
catch (SocketException e) ... {
E.printstacktrace ();
System.exit (-1);
}
BufferedReader typereader = new BufferedReader (
New InputStreamReader (system.in)
);
Long data = 0;
while (true) ... {
Bytearrayoutputstream bytesout = new Bytearrayoutputstream ();
DataOutputStream dataout = new DataOutputStream (bytesout);
Try ... {
Data =<

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.