Java Socket編程執行個體(二)- UDP基本使用_java

來源:互聯網
上載者:User

一.服務端代碼:

import java.io.*; import java.net.*;  public class UDPEchoServer {    private static final int ECHOMAX = 255; // Maximum size of echo datagram    public static void main(String[] args) throws IOException {      int servPort = 5500; // Server port      DatagramSocket socket = new DatagramSocket(servPort);     DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);      while (true) { // Run forever, receiving and echoing datagrams       socket.receive(packet); // Receive packet from client       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 */   } } 

二.用戶端代碼:

import java.net.*; import java.io.*;  public class UDPEchoClientTimeout {    private static final int TIMEOUT = 3000; // Resend timeout (milliseconds)   private 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, World".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.length);      int tries = 0; // Packets may be lost, so we have to keep trying     boolean receivedResponse = false;     do {       socket.send(sendPacket); // Send the echo string       try {         socket.receive(receivePacket); // Attempt echo reply reception          if (!receivePacket.getAddress().equals(serverAddress)) {// Check                                     // source           throw new IOException("Received packet from an unknown source");         }         receivedResponse = true;       } 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();   }} 

上述代碼的UDP服務端是單線程,一次只能服務一個用戶端。

以上就是本文的全部內容,查看更多Java的文法,大家可以關註:《Thinking in Java 中文手冊》、《JDK 1.7 參考手冊官方英文版》、《JDK 1.6 API java 中文參考手冊》、《JDK 1.5 API java 中文參考手冊》,也希望大家多多支援雲棲社區。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.