자바 UDP 데이터 신문 과 Socket

두 핵심 클래스 DatagramPacket 패 킷 패 킷,DatagramSocket 패 킷 Socket
패 킷 을 받 는 구조 함수
public DatagramPacket(byte buf[], int length)
패 킷 을 보 내 는 구조 함수 가 수신 한 것 보다 대상 주 소 를 더 많이 보 냅 니 다.
public DatagramPacket(byte buf[], int length, InetAddress address, int port)
두 가지 핵심 방법 DatagramSocket 류
public void send(DatagramPacket p) throws IOException
public synchronized void receive(DatagramPacket p) throws IOException
모두 void 입 니 다.보 내 고 받 은 데 이 터 는 DatagramPacket 에 포 장 됩 니 다.
일부 유용 한 응용 프로그램
//  UDP   ,         ,      
public class SimpleUDPClient {

  private int bufferSize;
  private DatagramSocket socket;
  private DatagramPacket out;

  public SimpleUDPClient(InetAddress host, int port, int bufferSize, 
      int timeout) throws SocketException {
    out = new DatagramPacket(new byte[1], 1, host, port);
    this.bufferSize = bufferSize;
    socket = new DatagramSocket(0);
    socket.connect(host, port);
    socket.setSoTimeout(timeout);
  }

  public SimpleUDPClient(InetAddress host, int port) throws SocketException {
    this(host, port, 8192, 300000);
  }

  public byte[] request() {
    DatagramPacket in;
    try {
      socket.send(out);
      in = new DatagramPacket(new byte[bufferSize], bufferSize);
      socket.receive(in);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return in.getData();
  }

  public static void main(String[] args) {
    InetAddress host = null;
    int port = 0;
    try {
      port = Integer.parseInt(args[0]);
      host = InetAddress.getByName(args[1]);
      port = Integer.parseInt("13");
      if (port < 1 || port > 65535)
        throw new Exception("     ");
    } catch (Exception e) {
      try {
        host = InetAddress.getByName("localhost");
        port = 13;
      } catch (UnknownHostException e1) {
      }
    }
    try {
      SimpleUDPClient client = new SimpleUDPClient(host, port);
      byte[] response = client.request();
      String result;
      try {
        result = new String(response, "ASCII");
      } catch (UnsupportedEncodingException e) {
        result = new String(response, "8859_1");
      }
      System.out.println(result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

//    UDPServer,               ,
//   public abstract void response(DatagramPacket request)  
public abstract class BaseUDPServer extends Thread {

  private int bufferSize;
  protected DatagramSocket socket;

  public BaseUDPServer(int bufferSize, int port) throws SocketException {
    this.bufferSize = bufferSize;
    socket = new DatagramSocket(port);
  }

  public BaseUDPServer(int port) throws SocketException {
    this(8192, port);
  }

  public void run() {
    byte[] buf = new byte[bufferSize];
    while (true) {
      DatagramPacket in = new DatagramPacket(buf, bufferSize);
      try {
        socket.receive(in);
        this.response(in);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

  public abstract void response(DatagramPacket request);
}

//  BaseUDPServer ,   daytime   server
public class DayTimeServer extends BaseUDPServer {

  private static final int DEFAULT_PORT = 13;

  public DayTimeServer() throws SocketException {
    super(DEFAULT_PORT);
  }

  public void response(DatagramPacket request) {
    try {
      String date = new Date() + "\r
"; byte[] data = date.getBytes("ASCII"); DatagramPacket response = new DatagramPacket(data, data.length, request.getAddress(), request.getPort()); socket.send(response); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) { try { BaseUDPServer server = new DayTimeServer(); server.start(); } catch (SocketException e) { throw new RuntimeException(e); } } }

echo 프로 토 콜
TCP 기반 echo 클 라 이언 트 는 메 시 지 를 보 낸 다음 같은 연결 에서 응답 을 기다 릴 수 있 습 니 다.그러나 UDP 기반 echo 클 라 이언 트 는 보 내 는 메 시 지 를 항상 받 을 수 있다 고 보장 할 수 없습니다.따라서 비동기 적 으로 데 이 터 를 보 내 고 받 아들 여야 한다.
public class UDPEchoServer extends UDPServer {

  public final static int DEFAULT_PORT = 7;

  public UDPEchoServer() throws SocketException {
    super(DEFAULT_PORT);
  }

  public void respond(DatagramPacket packet) {
    try {
      DatagramPacket outgoing = new DatagramPacket(packet.getData(), packet.getLength(), 
          packet.getAddress(), packet.getPort());
      socket.send(outgoing);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }

  public static void main(String[] args) {
    try {
      UDPServer server = new UDPEchoServer();
      server.start();
    } catch (SocketException ex) {
      System.err.println(ex);
    }
  }
}

public class UDPEchoClient {

  private static final int DEFAULT_PORT = 7;

  public static void main(String[] args) {
    String hostname = "localhost";
    int port = DEFAULT_PORT;
    if (args.length > 0) {
      hostname = args[0];
    }
    try {
      DatagramSocket socket = new DatagramSocket();
      InetAddress address = InetAddress.getByName(hostname);
      socket.connect(address, port);
      SenderThread sender = new SenderThread(socket, address, DEFAULT_PORT);
      sender.start();
      Thread receiver = new ReceiverThread(socket);
      receiver.start();
    } catch (SocketException e) {
      throw new RuntimeException(e);
    } catch (UnknownHostException e) {
      throw new RuntimeException(e);
    }
  }
}

public class SenderThread extends Thread {

  private DatagramSocket socket;
  private InetAddress address;
  private int port;
  private boolean stopped = false;

  public SenderThread(DatagramSocket socket, InetAddress address, int port) {
    this.socket = socket;
    this.address = address;
    this.port = port;
  }

  public void halt() {
    this.stopped = true;
  }

  public void run() {
    Scanner sc = new Scanner(System.in);
    while (true) {
      if (stopped) return;
      String input = sc.nextLine();
      if (input.equals("."))
        break;
      byte[] in = input.getBytes();
      DatagramPacket request = new DatagramPacket(in, in.length, address, port);
      try {
        socket.send(request);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      Thread.yield();
    }
  }
}

public class ReceiverThread extends Thread {

  private DatagramSocket socket;
  private boolean stopped = false;

  public void halt() {
    this.stopped = true;
  }

  public ReceiverThread(DatagramSocket socket) {
    this.socket = socket;
  }

  public void run() {
    byte[] buffer = new byte[65507];
    while (true) {
      if (stopped) return;
      DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
      try {
        socket.receive(dp);
        String s = new String(dp.getData(), 0, dp.getLength());
        System.out.println(s);
        Thread.yield();
      } catch (IOException ex) {
        System.err.println(ex);
      }
    }
  }
}

public abstract class UDPServer extends Thread {

  private int bufferSize; // in bytes
  protected DatagramSocket socket;

  public UDPServer(int port, int bufferSize) throws SocketException {
    this.bufferSize = bufferSize;
    this.socket = new DatagramSocket(port);
  }

  public UDPServer(int port) throws SocketException {
    this(port, 8192);
  }

  public void run() {
    byte[] buffer = new byte[bufferSize];
    while (true) {
      DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
      try {
        socket.receive(incoming);
        this.respond(incoming);
      } catch (IOException ex) {
        System.err.println(ex);
      }
    } // end while
  } // end run

  public abstract void respond(DatagramPacket request);
}

좋은 웹페이지 즐겨찾기