# FastNio
**Repository Path**: xcode_xiao/FastNio
## Basic Information
- **Project Name**: FastNio
- **Description**: 使用Kotlin编写的基于NIO的通信框架
- **Primary Language**: Unknown
- **License**: LGPL-3.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2020-10-20
- **Last Updated**: 2022-06-02
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# FastNio
#### 介绍
使用Kotlin编写的基于NIO的通信框架
#### 软件架构
核心库:library -> 纯kotlin编写的NIO通信框架。
http:基于library基础上实现了部分http协议,有http功能的示例。
#### 使用说明
1. 实现```IClientAdapterFactory```接口,或者可以直接使用```SingleClientAdapterFactory```或者```CacheClientAdapterFactory```
2. 实现```IClientAdapter```,或者直接使用```EchoClientAdapter```
3. 要实现自定义协议则需要实现```IProtocol```
示例:
```kotlin
/**
* 自定义协议的解码器。
* 字符串的协议解码器
*/
class StringProtocol : IProtocol
{
/**
* 自定义协议的解码函数
* @param session 会话的句柄
* @param byteArray 传入的字节数组
* @param len 字节数组的可读长度
* @return 返回的自定义协议的实体,如果没有解析完,则返回 null
*/
override fun decode(session: Session, byteArray: ByteArray, len: Int): String?
{
return String(byteArray, 0, len)
}
override fun onClear() = Unit
}
/**
* 在控制台输出文字,或者其他业务逻辑处理
*/
class EchoClientAdapter : ProtocolClientAdapter(StringProtocol::class)
{
override fun onSessionCreate(session: Session)
{
println("打开会话:${session.sessionId},${Thread.currentThread().name}")
}
override fun onSessionReceive(session: Session, data: String)
{
println("读取会话:${data},${Thread.currentThread().name}")
session.write("服务端已收到:$data".toByteArray())
}
override fun onSessionClose(session: Session)
{
println("关闭会话:${session.sessionId},${Thread.currentThread().name}")
}
}
/**
* 单例的客户端适配器,
* 如果想区分每个会话都有单独的处理类,那么就需要保存 ssId 和 IClientAdapter 之间的映射关系
* 如果不想区分,而是不关心数据的来源,则可以使用同一个 IClientAdapter 即单例就好了
*/
class SingleClientAdapterFactory(private val klass: KClass) : IClientAdapterFactory
{
private val adapter by lazy {
klass.createInstance()
}
override fun get(ssId: String) = adapter
override fun has(ssId: String) = true
override fun remove(ssId: String) = Unit
}
/**
* 启动服务
*/
NioServer.setPort(8080)
.setClientAdapterFactory(SingleClientAdapterFactory(EchoClientAdapter::class))
.start()
```
### Http的使用
Http包只是基于library,Http的协议的支持。
```kotlin
http {
// 设置端口
port = 8000
// 普通网页接口
get("/") { request, response ->
val lastTime = request.httpSession["lastTime"]
response.writeHtml("Hello World 上次时间:$lastTime")
request.httpSession["lastTime"] = Date()
}
// 下载文件接口
get("download") { _, response ->
response.sendRedirect("/")
}
// 设置静态文件夹
static("/Users/xiaolei/IdeaProjects/FastNio/src/main/resources")
// 设置首页的Uri
setIndex("/index.html")
// 设置临时文件夹
tempDir = File("/Users/xiaolei/IdeaProjects/FastNio/src/main/resources/tmp")
}
```