aio-socket 使用文档
快速开始
IDEA 新建Maven空项目:File->New->Project…->Maven->Next->Finish
引入Maven
<dependency>
<groupId>io.github.mxd888.socket</groupId>
<artifactId>aio-socket-kernel</artifactId>
<version>3.8.5.v20221001-RELEASE</version>
</dependency>
新建DemoPacket并继承Packet
public class DemoPacket extends Packet {
private String data;
public DemoPacket(String data) {
this.data = data;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
新建DemoHandler并实现接口AioHandler
public class DemoHandler implements AioHandler {
@Override
public Packet handle(ChannelContext channelContext, Packet packet) {
return null;
}
@Override
public Packet decode(MemoryUnit memoryUnit, ChannelContext channelContext) {
ByteBuffer buffer = memoryUnit.buffer();
int remaining = buffer.remaining();
if (remaining < Integer.BYTES) {
return null;
}
buffer.mark();
int length = buffer.getInt();
byte[] b = AIOUtil.getBytesFromByteBuffer(length, memoryUnit, channelContext);
if (b == null) {
buffer.reset();
return null;
}
return new DemoPacket(new String(b, StandardCharsets.UTF_8));
}
@Override
public void encode(Packet packet, ChannelContext channelContext) {
if (packet instanceof DemoPacket) {
DemoPacket demoPacket = (DemoPacket) packet;
// 自定义协议
WriteBuffer writeBuffer = channelContext.getWriteBuffer();
try {
writeBuffer.writeInt(demoPacket.getData().getBytes().length);
writeBuffer.write(demoPacket.getData().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
新建ServerHandler并继承DemoHandler
public class ServerHandler extends DemoHandler {
@Override
public Packet handle(ChannelContext channelContext, Packet packet) {
if (packet instanceof DemoPacket) {
return packet;
}
return null;
}
}
新建Server启动类
public class Server {
public static void main(String[] args) {
ServerBootstrap bootstrap = new ServerBootstrap("localhost", 8888, new ServerHandler());
bootstrap.setMemoryPoolFactory(() -> new MemoryPool(2 * 1024 * 1024, 2, true))
.setReadBufferSize(1024 * 2)
.setWriteBufferSize(1024 * 2, 512)
.start();
}
}
新建ClientHandler并继承DemoHandler
public class ClientHandler extends DemoHandler {
@Override
public Packet handle(ChannelContext channelContext, Packet packet) {
if (packet instanceof DemoPacket) {
DemoPacket packet1 = (DemoPacket) packet;
System.out.println("收到消息:" + packet1.getData());
}
return null;
}
}
新建Client启动类
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
DemoPacket demoPacket = new DemoPacket("hello aio-socket");
ClientBootstrap bootstrap = new ClientBootstrap("localhost", 8888, new ClientHandler());
ChannelContext channelContext = bootstrap.setBufferFactory(() -> new MemoryPool(1024 * 1024, 1, true))
.setReadBufferSize(1024 * 2)
.setWriteBufferSize(1024 * 2, 512)
.start();
// 发送消息
Aio.send(channelContext, demoPacket);
Thread.sleep(1000);
// 关机
bootstrap.shutdown();
}
}
高级使用
尽情期待