Program | network
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 ();
}
}