The use of java.net is very useful for applications interspersed with IO streams.

Source: Internet
Author: User

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 the port number to avoid conflict with other applications
CLI = new datagramsocket (10002 );
SB = new byte [1024];
Sen = "send data in UDP mode ";
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 ();
}
}
Receiver data:
// Improve the Code to change the Receiving Method
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) // loop if no data exists
{
Ser. Receive (PAC );
I = Pac. getlength ();
// Receive data
If (I> 0)
{
// Specify the length of the received data, so that the received data can be displayed normally. This can be easily ignored at the beginning.
REV = new string (RB, 0, Pac. getlength ());
System. Out. println (REV );
I = 0; // receive cyclically
}
}
}
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.