举报投诉联系我们 手机版 热门标签 名动网
您的位置:名动网 > java 套接字 Java 数据报套接字通道

java 套接字 Java 数据报套接字通道

2023-03-18 02:20 Java教程

java 套接字 Java 数据报套接字通道

java 套接字

Java 套接字是 Java 编程语言中的一种网络通信机制,它允许两台计算机之间进行双向通信。它是基于 TCP/IP 协议的,可以用来在两台计算机之间传递数据。Java 套接字使用 Java 类库中的 Socket 类来实现,它提供了一个标准的 API 来创建、配置和使用套接字。

Java 套接字可以用来在不同的节点上进行通信,也可以在同一个节点上进行通信。它允许应用程序使用标准的 Java 类库来创建、配置和使用套接字,而无需考虑底层协议或者平台特定性。

Java 套接字有两个重要的子类:ServerSocket 和 Socket。ServerSocket 用于监听端口(端口是一个整数)上的连接请求;Socket 用于处理已连接到端口上的请求。当 ServerSocket 收到连接请求时,它会创建一个新的 Socket 并将其返回作为新连接的处理对象。

// Create a server socket 
ServerSocket server = new ServerSocket(port); 
// Wait for a connection 
Socket connection = server.accept(); 
// Get input and output streams 
InputStream in = connection.getInputStream(); 
OutputStream out = connection.getOutputStream(); 

Java 数据报套接字通道

Java网络教程 - Java数据报套接字通道


java.nio.channels.DatagramChannel类表示数据报通道。默认情况下,它是阻塞。要使其无阻塞,请使用configureBlocking(false)方法。

要创建 DatagramChannel ,请调用其 open()静态方法之一。

要将其用于IP多播,请将多播组的地址类型指定为其 open()方法的参数。

open()方法创建一个没有连接的DatagramChannel对象。

例子

以下代码显示如何基于数据报通道创建Echo服务器。

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    DatagramChannel server = null;
    server = DatagramChannel.open();
    InetSocketAddress sAddr = new InetSocketAddress("localhost", 8989);
    server.bind(sAddr);
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    while (true) {
      System.out.println("Waiting for a  message  from"
          + "  a  remote  host at " + sAddr);
      SocketAddress remoteAddr = server.receive(buffer);
      buffer.flip();
      int limits = buffer.limit();
      byte bytes[] = new byte[limits];
      buffer.get(bytes, 0, limits);
      String msg = new String(bytes);

      System.out.println("Client at " + remoteAddr + "  says: " + msg);
      buffer.rewind();
      server.send(buffer, remoteAddr);
      buffer.clear();
    }
    //server.close();
  }
}

上面的代码生成以下结果。


例2

以下代码基于数据报通道创建客户端程序。

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    DatagramChannel client = null;
    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();
    client.receive(buffer);
    buffer.flip();
    int limits = buffer.limit();
    byte bytes[] = new byte[limits];
    buffer.get(bytes, 0, limits);
    String response = new String(bytes);
    System.out.println("Server  responded: " + response);
    client.close();
  }
}

上面的代码生成以下结果。


列出机器上的可用网络接口

import java.net.NetworkInterface;
import java.util.Enumeration;

public class Main {
  public static void main(String[] args) throws Exception {
    Enumeration<NetworkInterface> e = NetworkInterface
        .getNetworkInterfaces();
    while (e.hasMoreElements()) {
      NetworkInterface nif = e.nextElement();
      System.out.println("Name: " + nif.getName()
          + ",  Supports Multicast: " + nif.supportsMulticast()
          + ", isUp(): " + nif.isUp());
    }
  }
}

上面的代码生成以下结果。

例3

以下代码基于DatagramChannel的组播客户端程序

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.StandardProtocolFamily;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.MembershipKey;

public class Main {
  public static final String MULTICAST_IP = "239.1.1.1";
  public static final int MULTICAST_PORT = 8989;

  public static final String MULTICAST_INTERFACE_NAME = "eth1";

  public static void main(String[] args) throws Exception {
    MembershipKey key = null;
    DatagramChannel client = DatagramChannel.open(StandardProtocolFamily.INET);

    NetworkInterface interf = NetworkInterface.getByName(MULTICAST_INTERFACE_NAME);
    client.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    client.bind(new InetSocketAddress(MULTICAST_PORT));
    client.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    InetAddress group = InetAddress.getByName(MULTICAST_IP);
    key = client.join(group, interf);

    System.out.println("Joined the   multicast  group:" + key);
    System.out.println("Waiting for a  message  from  the"
        + "  multicast group....");

    ByteBuffer buffer = ByteBuffer.allocate(1048);
    client.receive(buffer);
    buffer.flip();
    int limits = buffer.limit();
    byte bytes[] = new byte[limits];
    buffer.get(bytes, 0, limits);
    String msg = new String(bytes);

    System.out.format("Multicast Message:%s%n", msg);
    key.drop();
  }
}

上面的代码生成以下结果。

例4

以下代码显示如何创建向多播组发送消息的基于DatagramChannel的组播程序。

import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
  public static final String MULTICAST_IP = "239.1.1.1";
  public static final int MULTICAST_PORT = 8989;
  public static final String MULTICAST_INTERFACE_NAME = "eth1";

  public static void main(String[] args) throws Exception {
    DatagramChannel server = DatagramChannel.open();
    server.bind(null);
    NetworkInterface interf = NetworkInterface
        .getByName(MULTICAST_INTERFACE_NAME);
    server.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    String msg = "Hello!";
    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
    InetSocketAddress group = new InetSocketAddress(MULTICAST_IP,
        MULTICAST_PORT);

    server.send(buffer, group);
    System.out.println("Sent the   multicast  message: " + msg);
  }
}

上面的代码生成以下结果。

阅读全文
以上是名动网为你收集整理的java 套接字 Java 数据报套接字通道全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
© 2024 名动网 mdwl.vip 版权所有 联系我们