Java programming Those things 106--network programming Technology 5

Source: Internet
Author: User

The function of the example is to implement the system time of the client program to the server side, and after the server receives the time, the feedback string "OK" to the client. The client code that implements this feature looks like this:

package UDP;
Import java.net.*
Import java.util.*
/**
* Simple UDP client, implement system time function to server side
*/
  public class Simpleudpclient {
public static void Main (string[] args) {
Datagramsocket ds = null; The Connection object
Datagrampacket SENDDP;//Send Packet object
Datagrampacket RECEIVEDP;//Receive Packet object
String serverhost = "127.0.0 .1 ";  server IP
int serverport = 10010;    The server port number
try{
//establishes the connection
ds = new Datagramsocket ();
Initialize send data
Date d = new Date ();//Current time
String content = D.tostring ();//Convert to String
byte[] data = CONTENT.G Etbytes ();    
//Initialize Send package object
InetAddress address = Inetaddress.getbyname (serverhost);
SENDDP = new Datagrampacket (data,data.length,address,serverport);
//Send
Ds.send (SENDDP);
   
//initialization receive data
Byte[] b = new byte[1024];
RECEIVEDP = new Datagrampacket (b,b.length);    
//Receive
Ds.receive (RECEIVEDP);
Reads the feedback content and outputs the
byte[] response = RECEIVEDP.GEtdata ();
int len = Receivedp.getlength ();
String s = new string (Response,0,len);
System.out.println ("Server-side feedback is:" + s);   
}catch (Exception e) {
E.printstacktrace ();
    }finally{
try{
//close connection
Ds.close ();
}catch (Exception e) {}
}
}
}

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.