Using Java to write simple UDP network communication programs

Source: Internet
Author: User

Java encapsulates a large number of socket APIs, which provide great convenience for writing network communication programs.
In the study of computer network, we have mastered the basic principle of tcp/udp, here is not to repeat. The source code for the receiver and the sender is given for discussion and criticism.
The sending end code is as follows:
You can send data as soon as you have a slight improvement
Import java.io.*;
Import java.lang.*;
Import java.net.*;
public class Uclient
{
Private Datagramsocket CLI;
Private Datagrampacket PAC;
private byte sb[];
Private String Sen;
Public Uclient ()
{
Init ();
}
public void Init ()
{
Try
{
Specify a port number to avoid conflicts with other applications
Cli=new Datagramsocket (10002);
Sb=new byte[1024];
sen= "UDP send Data";
Sb=sen.getbytes ();
Pac=new Datagrampacket (Sb,sb.length,inetaddress.getbyname ("localhost"), 10005);
Cli.send (PAC);
}
catch (SocketException se)
{
Se.printstacktrace ();
}
catch (IOException IE)
{
Ie.printstacktrace ();
}
}
public static void Main (String args[])
{
New Uclient ();
}
}
Receive-Side data:
Improve your code to change the way you receive
Import java.io.*;
Import java.lang.*;
Import java.net.*;
public class Userve
{
Private Datagramsocket ser;
Private Datagrampacket PAC;
private byte rb[];
Private String rev;
Public Userve ()
{
Init ();
}
public void Init ()
{
Try
{
Ser=new Datagramsocket (10005);
Rb=new byte[1024];
Pac=new Datagrampacket (rb,rb.length);
Rev= "";
int i=0;
while (i==0)//No data, the loop
{
Ser.receive (PAC);
I=pac.getlength ();
Receive data
if (i>0)
{
Specifies the length of the data to be received so that the received data is displayed properly and can easily be overlooked at first
Rev=new String (Rb,0,pac.getlength ());
System.out.println (rev);
i=0;//Loop Receive
}
}
}
catch (Exception e)
{
E.printstacktrace ();
}
}
public static void Main (String args[])
{
New Userve ();
}
}

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.