Java Socket 프로그래밍 인스턴스(2) - UDP 기본 사용

3790 단어 JavaSocketUDP
하나.서버 코드:

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 */ 
  } 
} 
2.클라이언트 코드:

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 자바 중국어 참조 안내서 》,많은 응원 부탁드립니다.

좋은 웹페이지 즐겨찾기