Java Socket Programming Instance (ii)-UDP basic use _java

Source: Internet
Author: User
Tags server port

One. Service-side code:

Import java.io.*; 
Import java.net.*; 
 
public class Udpechoserver { 
 
  private static final int echomax = 255://Maximum size of Echo datagram public 
 
  Stati c void Main (string[] args) throws IOException { 
 
    int servport = 5500;//Server port 
 
    datagramsocket socket = new Da Tagramsocket (servport); 
    Datagrampacket packet = new Datagrampacket (new Byte[echomax), Echomax); 
 
    while (true) {//Run forever, receiving and echoing datagrams 
      socket.receive (packet);//Receive packet from client< C11/>SYSTEM.OUT.PRINTLN ("Handling client at" + packet.getaddress (), gethostaddress () + "on port" + Packet.getport ()); 
   socket.send (packet); Send the same packet back to client 
      packet.setlength (Echomax);/Reset length to avoid shrinking buffer 
    }
   /* not reached */ 
  } 

Two. Client code:

Import java.net.*; 
 
Import java.io.*; public class Udpechoclienttimeout {private static final int TIMEOUT = 3000;//Resend TIMEOUT (milliseconds) priv ATE static final int maxtries = 5;  Maximum retransmissions public static void Main (string[] args) throws IOException {inetaddress serveraddress = Inetaddress.getbyname ("127.0.0.1"); Server address int servport = 5500; Server Port//Convert The argument String to bytes using the default encoding byte[] Bytestosend = "Hi, worl 
 
    D ". GetBytes (); 
    Datagramsocket socket = new Datagramsocket (); Socket.setsotimeout (TIMEOUT); Maximum Receive blocking time (milliseconds)//sending packet Datagrampacket Sendpacket = new Datagrampacket ( 
 
    Bytestosend, Bytestosend.length, serveraddress, Servport); Datagrampacket Receivepacket =//Receiving packet new Datagrampacket (new Byte[bytestosend.length), Bytestosend.lengt 
 
    h); int tries = 0; Packets May is lost, so we haveTo keep trying boolean receivedresponse = false; do {socket.send (sendpacket);//Send the Echo string try {socket.receive (receivepacket);//Attem 
                                    PT Echo Reply Reception if (!receivepacket.getaddress (). Equals (ServerAddress)) {//Check 
        SOURCE throw new IOException ("Received packet from a unknown source"); 
      } Receivedresponse = true; 
        The catch (Interruptedioexception e) {//We did not get anything tries + = 1; 
      System.out.println ("Timed Out," + (maxtries-tries) + "more tries ..."); 
 
    } while ((!receivedresponse) && (Tries < maxtries)); 
    if (receivedresponse) {System.out.println ("Received:" + New String (Receivepacket.getdata ())); 
    else {System.out.println ("No response-giving up."); 
  } socket.close (); 

 }
}

The UDP server for the above code is single-threaded and can only serve one client at a time.

The above is the entire contents of this article, see more Java syntax, you can pay attention to: "Thinking in the Java Chinese manual", "JDK 1.7 reference manual in the official English version", "JDK 1.6 API Java Chinese Reference manual", "JDK 1.5 API Java Chinese Ginseng Test Manual, but also hope that we support the cloud habitat community.

Related Article

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.