欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java Socket编程实例(五)- NIO UDP实践

程序员文章站 2024-03-12 19:58:20
一、回传协议接口和udp方式实现: 1.接口: import java.nio.channels.selectionkey; import java.io....

一、回传协议接口和udp方式实现:

1.接口:

import java.nio.channels.selectionkey; 
import java.io.ioexception; 
 
public interface echoprotocol { 
 void handleaccept(selectionkey key) throws ioexception; 
 void handleread(selectionkey key) throws ioexception; 
 void handlewrite(selectionkey key) throws ioexception; 
} 

2.实现:

import java.net.socketaddress; 
import java.nio.channels.*; 
import java.nio.bytebuffer; 
import java.io.ioexception; 
 
public class udpechoselectorprotocol implements <span style="font-size: 1em; line-height: 1.5;">echoprotocol </span><span style="font-size: 1em; line-height: 1.5;">{</span> 
  private static final int echomax = 255; // maximum size of echo datagram 
 
  static class clientrecord { 
    public socketaddress clientaddress; 
    public bytebuffer buffer = bytebuffer.allocate(echomax); 
  } 
 
  public void handleaccept(selectionkey key) throws ioexception { 
     
  } 
 
  public void handleread(selectionkey key) throws ioexception { 
    datagramchannel channel = (datagramchannel) key.channel(); 
    clientrecord clntrec = (clientrecord) key.attachment(); 
    clntrec.buffer.clear(); // prepare buffer for receiving 
    clntrec.clientaddress = channel.receive(clntrec.buffer); 
    if (clntrec.clientaddress != null) { // did we receive something? 
      // register write with the selector 
      key.interestops(selectionkey.op_write); 
    } 
  } 
 
  public void handlewrite(selectionkey key) throws ioexception { 
    datagramchannel channel = (datagramchannel) key.channel(); 
    clientrecord clntrec = (clientrecord) key.attachment(); 
    clntrec.buffer.flip(); // prepare buffer for sending 
    int bytessent = channel.send(clntrec.buffer, clntrec.clientaddress); 
    if (bytessent != 0) { // buffer completely written? 
      // no longer interested in writes 
      key.interestops(selectionkey.op_read); 
    } 
  } 
 
}

二、nio udp客户端:

import java.net.inetsocketaddress; 
import java.net.socketexception; 
import java.nio.bytebuffer; 
import java.nio.channels.datagramchannel; 
 
public class udpechoclientnonblocking { 
 
  private static final int timeout = 3000; // resend timeout (milliseconds) 
  private static final int maxtries = 255; // maximum retransmissions 
   
  public static void main(string args[]) throws exception { 
    // convert input string to bytes using the default charset 
    byte[] bytestosend = "0123456789abcdefghijklmnopqrstuvwxyz".getbytes(); 
 
    // create channel and set to nonblocking 
    datagramchannel datagramchannel = datagramchannel.open(); 
    datagramchannel.configureblocking(false); 
    datagramchannel.socket().setsotimeout(timeout); 
     
    bytebuffer writebuf = bytebuffer.wrap(bytestosend); 
    bytebuffer readbuf = bytebuffer.allocate(maxtries); 
     
    datagramchannel = datagramchannel.connect(new inetsocketaddress("127.0.0.1", 5500)); 
 
    int totalbytesrcvd = 0; // total bytes received so far 
    int bytesrcvd; // bytes received in last read 
    while (totalbytesrcvd < bytestosend.length) { 
      if (writebuf.hasremaining()) { 
        datagramchannel.write(writebuf); 
      } 
      if ((bytesrcvd = datagramchannel.read(readbuf)) == -1) { 
        throw new socketexception("connection closed prematurely"); 
      } 
      totalbytesrcvd += bytesrcvd; 
      system.out.print("."); // do something else 
    } 
 
    system.out.println("received: " + new string(readbuf.array(), 0, totalbytesrcvd)); 
    datagramchannel.close(); 
  } 
}

三、nio udp服务端:

import java.io.ioexception; 
import java.net.inetsocketaddress; 
import java.nio.channels.*; 
import java.util.iterator; 
 
public class udpechoserverselector { 
 
  private static final int timeout = 3000; // wait timeout (milliseconds) 
 
  public static void main(string[] args) throws ioexception { 
    // create a selector to multiplex client connections. 
    selector selector = selector.open(); 
 
    datagramchannel channel = datagramchannel.open(); 
    channel.configureblocking(false); 
    channel.socket().bind(new inetsocketaddress(5500)); 
    channel.register(selector, selectionkey.op_read, new udpechoselectorprotocol.clientrecord()); 
 
    udpechoselectorprotocol echoselectorprotocol = new udpechoselectorprotocol(); 
    while (true) { // run forever, receiving and echoing datagrams 
      // wait for task or until timeout expires 
      if (selector.select(timeout) == 0) { 
        system.out.print("."); 
        continue; 
      } 
 
      // get iterator on set of keys with i/o to process 
      iterator<selectionkey> keyiter = selector.selectedkeys().iterator(); 
      while (keyiter.hasnext()) { 
        selectionkey key = keyiter.next(); // key is bit mask 
 
        // client socket channel has pending data? 
        if (key.isreadable()) 
          echoselectorprotocol.handleread(key); 
 
        // client socket channel is available for writing and 
        // key is valid (i.e., channel not closed). 
        if (key.isvalid() && key.iswritable()) 
          echoselectorprotocol.handlewrite(key); 
 
        keyiter.remove(); 
      } 
    } 
  } 
 
}

以上就是本文的全部内容,查看更多java的语法,大家可以关注:《thinking in java 中文手册》、《jdk 1.7 参考手册官方英文版》、《jdk 1.6 api java 中文参考手册》、《jdk 1.5 api java 中文参考手册》,也希望大家多多支持。