集册 Java实例教程 基于数据报通道的客户端程序

基于数据报通道的客户端程序

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

464
基于数据报通道的客户端程序

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.DatagramChannel;

/**来自 
 时 代 J a v a**/

public class Main {

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

    DatagramChannel client = DatagramChannel.open();

    client.bind(null);

    String msg = "Hello";

    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());

    InetSocketAddress serverAddress = new InetSocketAddress("localhost", 8989);

    client.send(buffer, serverAddress);

    buffer.clear();
    /* 
     来自 
    *时代Java*/

    client.receive(buffer);

    buffer.flip();

    int limits = buffer.limit();

    byte bytes[] = new byte[limits];

    buffer.get(bytes, 
展开阅读全文