集册 Java实例教程 基于UDP套接字的Echo客户端

基于UDP套接字的Echo客户端

欢马劈雪     最近更新时间:2020-01-02 10:19:05

557
基于UDP套接字的Echo客户端

import java.io.BufferedReader;
/* 
 来自 
*N  o w  J a v a . c o m*/

import java.io.InputStreamReader;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.UnknownHostException;


public class Main {

  public static void main(String[] args) throws Exception {

    DatagramSocket udpSocket = new DatagramSocket();

    String msg = null;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String promptMsg = "Please enter a message (Bye to quit):";

    System.out.print(promptMsg);

    while ((msg = br.readLine()) != null) {

      if (msg.equalsIgnoreCase("bye")) {

        break;

      }

      DatagramPacket packet = getPacket(msg);

      udpSocket.send(packet);

      udpSocket.receive(packet);// 来自 时代Java公众号

      displayPacketDetails(packet);

      System.out.print(promptMsg);

    }

    udpSocket.close();

  }


  public static void displayPacketDetails(DatagramPacket packet) {

    byte[] msgBuffer = packet.getData();

    int length = packet.getLength();

    int offset = packet.getOffset();

    int remotePort = packet.getPort();

    InetAddress remoteAddr = packet.getAddress();

    String msg = new String(msgBuffer, offset, length);

    System.out.println("[Server at IP Address=" + remoteAddr + ", port="

        + remotePort + "]: " + msg);


    System.out.println();

  }


  public static DatagramPacket getPacket(String msg)

      throws UnknownHostException {

    final int PACKET_MAX_LENGTH = 1024;

    byte[] msgBuffer = msg.getBytes();


    int length = msgBuffer.length;

    if (length > PACKET_MAX_LENGTH) {

      length 
展开阅读全文