ChannelTest.java
2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package cn.org.hentai.jtt1078.test;
import cn.org.hentai.jtt1078.util.ByteHolder;
import cn.org.hentai.jtt1078.util.ByteUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
/**
* Created by matrixy on 2020/1/9.
*/
public class ChannelTest implements ByteChannel
{
byte[] temp = new byte[4];
ByteHolder buffer = new ByteHolder(1024);
// 读出,存入dst
@Override
public int read(ByteBuffer dst) throws IOException
{
dst.flip();
int len = Math.min(4, buffer.size());
if (dst.remaining() > len)
{
buffer.sliceInto(temp, len);
dst.put(temp, 0, len);
}
else
{
// 丢掉???
}
dst.flip();
return len;
}
// 从src读出,写入进来
@Override
public int write(ByteBuffer src) throws IOException
{
int len = -1;
// src.flip();
len = Math.min(4, src.limit());
src.get(temp, 0, len);
buffer.write(temp, 0, len);
// src.flip();
System.out.println("write: " + len);
return len;
}
@Override
public boolean isOpen()
{
return true;
}
@Override
public void close() throws IOException
{
}
public byte[] array()
{
return buffer.array();
}
public static void main(String[] args) throws Exception
{
ChannelTest chl = new ChannelTest();
ByteBuffer buffer = ByteBuffer.allocate(4);
java.nio.ByteBuffer xx;
System.out.println(buffer.getClass().getName());
for (int i = 0; i < 4096; i++)
buffer.put((byte)'f');
/*
buffer.putLong(0x1122334455667788L);
buffer.flip();
// flip太迷惑了
buffer.isReadOnly();
int len = chl.write(buffer);
len = chl.write(buffer);
ByteUtils.dump(chl.array());
*/
}
static final class ByteBufferWrapper
{
boolean writeMode;
ByteBuffer buffer;
private ByteBufferWrapper(int size)
{
this.buffer = ByteBuffer.allocate(size);
}
// 控制写入,代理过来
public void write()
{
}
// 写出就无所谓了
public static ByteBufferWrapper create(int size)
{
return new ByteBufferWrapper(size);
}
}
}