Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/
Client:
Import java.net. datagrampacket;
Import java.net. datagramsocket;
Import java.net. inetaddress;
Import java.net. socketexception;
Import java.net. unknownhostexception;
Import java. Io. ioexception;
Public class udpclient {
Public static void main (string Arg []) {
String outstr;
If (Arg. length> = 1)
Outstr = Arg [0];
Else
Outstr = "count ";
Try {
Datagramsocket socket = new datagramsocket ();
Byte outblock [] = outstr. getbytes ();
Inetaddress address = inetaddress. getlocalhost ();
Datagrampacket outpacket =
NewDatagrampacket (outblock, outblock. length, address, 8765 );
Socket. Send (outpacket );
System. Out. println ("client sent:" + outstr );
Byte inblock [] = new byte [256];
Datagrampacket inpacket =
New datagrampacket (inblock, inblock. Length );
Socket. Receive (inpacket );
String instr = new string (inpacket. getdata (), 0, inpacket. getlength ());
System. Out. println ("client got:" + instr );
Socket. Close ();
} Catch (socketexception e ){
System. Out. println (E );
} Catch (unknownhostexception e ){
System. Out. println (E );
} Catch (ioexception e ){
System. Out. println (E );
}
}
}
Server:
Import java.net. datagramsocket;
Import java.net. datagrampacket;
Import java.net. inetaddress;
Import java. Io. ioexception;
Import java. util. date;
Public class udpserver {
Public static void main (string Arg []) {
Datagramsocket socket = NULL;
Int COUNT = 0;
Try {
Socket = new datagramsocket (8765 );
} Catch (ioexception e ){
System. Out. println (E );
}
While (true ){
Try {
Byte block [] = new byte [256];
Datagrampacket inpacket
= New datagrampacket (block, block. Length );
Socket. Receive (inpacket );
Int length = inpacket. getlength ();
System. Out. println ("length of the data encoded ed:" + length );
Byte inblock [] = inpacket. getdata ();
String inmsg = new string (inblock, 0, length );
System. Out. println ("server got:" + inmsg );
Count ++;
String outmsg;
If (inmsg. Equals ("date ")){
Date = new date ();
Outmsg = date. tostring ();
} Else if (inmsg. Equals ("halt ")){
Socket. Close ();
Return;
} Else if (inmsg. Equals ("count ")){
Outmsg = "number of messages:" + count;
} Else {
Outmsg = "what is" + inmsg + "? ";
}
Byte outblock [] = outmsg. getbytes ();
Inetaddress returnaddress = inpacket. getaddress ();
Int returnport = inpacket. getport ();
Datagrampacket outpacket = new datagrampacket (
Outblock, outblock. length, returnaddress, returnport );
Socket. Send (outpacket );
} Catch (ioexception e ){
E. printstacktrace ();
}
}
}
}
Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/