集册 Java实例教程 基于UDP套接字的回声服务器

基于UDP套接字的回声服务器

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

524
基于UDP套接字的Echo服务器

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;
/** from 时 代 J     a    v  a - nowjava.com**/

public class Main {

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

    DatagramSocket udpSocket = new DatagramSocket(5555,

        InetAddress.getByName("localhost"));

    System.out.println("Created UDP server socket at "

        + udpSocket.getLocalSocketAddress() + "...");


    while (true) {

      System.out.println("Waiting for a UDP packet" + " to arrive...");

      DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);

      udpSocket.receive(packet);

      displayPacketDetails(packet);

      udpSocket.send(packet);

    }

  }


  public static void displayPacketDetails(DatagramPacket packet) {/* 来自 NowJava.com - 时  代  Java*/

    // Get the message

    byte[] msgBuffer = packet.getData();

    int length = packet.getLength();

    int offset = packet.getOffset();


    int remotePort = packet.getPort();

    InetAddress remoteAddr = packet.getAddress();

    
展开阅读全文