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

Java中channel用法总结

程序员文章站 2024-03-03 21:36:22
本文实例总结了java中channel用法。分享给大家供大家参考。具体分析如下: 1.channel接口的定义: public interface channe...

本文实例总结了java中channel用法。分享给大家供大家参考。具体分析如下:

1.channel接口的定义:

public interface channel
{
  public boolean isopen( );
  public void close( ) throws ioexception;
}

2.channel的常见类型:

filechannel, socketchannel, serversocketchannel, and datagramchannel;
filechannel通过randomaccessfile, fileinputstream, fileoutputstream的getchannel()来初始化。

socketchannel sc = socketchannel.open();
sc.connect (new inetsocketaddress ("somehost", someport));
serversocketchannel ssc = serversocketchannel.open( );
ssc.socket().bind (new inetsocketaddress (somelocalport));
datagramchannel dc = datagramchannel.open();

3.scatter/gather,必须使用bytebuffer.allocatedirect(100)

public interface scatteringbytechannel extends readablebytechannel {
  public long read (bytebuffer [] dsts) throws ioexception;
  public long read (bytebuffer [] dsts, int offset, int length) throws ioexception;
}
public interface gatheringbytechannel extends writablebytechannel {
  public long write(bytebuffer[] srcs) throws ioexception;
  public long write(bytebuffer[] srcs, int offset, int length) throws ioexception;
}

4.file lock是和file相关,而不是channel。可以对进程有效,而不是线程。可以通过内存映射文件(memory-mapped file)来实现线程同步

5.buffer = filechannel.map (filechannel.mapmode.read_only, 100, 200);

6.mappedbytebuffer are direct. load( )将整个文件加载到内存(改方法不能保证完成)。force( )将数据flush到硬盘。

7.未绑定端口的datagramchannel系统会自动分配端口。datagramchannel的connect(),将保证只接受指定源地址的数据包。这时候,可以使用普通的read和write方法,包括scatter/gather

希望本文所述对大家的java程序设计有所帮助。