集册 Java实例教程 编写UDP服务器

编写UDP服务器

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

534
编写UDP服务器

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.SocketAddress;
/**
nowjava - 时  代  Java
**/

import java.net.StandardProtocolFamily;

import java.net.StandardSocketOptions;

import java.nio.ByteBuffer;

import java.nio.channels.ClosedChannelException;

import java.nio.channels.DatagramChannel;


public class Main {


  public static void main(String[] args) {

    ByteBuffer echoText = ByteBuffer.allocateDirect(65507);

    try (DatagramChannel datagramChannel = DatagramChannel

        .open(StandardProtocolFamily.INET)) {

      if (datagramChannel.isOpen()) {/*N o  w  J a v a . c o m - 时  代  Java 提 供*/

        datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);

        datagramChannel.setOption(StandardSocketOptions.SO_SNDBUF, 4 * 1024);

        datagramChannel.bind(new InetSocketAddress("127.0.0.1", 5555));

        System.out.println("Echo server was binded on:"

            + datagramChannel.getLocalAddress());

        while (true) {

          SocketAddress clientAddress = datagramChannel.receive(echoText);

          echoText.flip();

          System.out.println("I have received " + echoText.limit()

              + " bytes from " + clientAddress.toString()

              + "! Sending them back ...");

          datagramChannel.send(echoText, clientAddress);

          echoText.clear();

        }

      } else {

        System.out.println("The channel cannot be opened!");

      }

    } catch (Exception ex) {

      if (ex instanceof ClosedChannelException) {

        System.err.println("The channel was unexpected closed ...");

      }

 
展开阅读全文