当前位置: 移动技术网 > IT编程>开发语言>Java > Java中channel用法总结

Java中channel用法总结

2019年07月22日  | 移动技术网IT编程  | 我要评论

血钻野燕麦的功效与作用,陈威翰图片,叶铭秋

本文实例总结了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程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网