riku
2019-09-23 5c570cef0cdefd4103b0d447f6505d4430807128
src/main/kotlin/com/flightfeather/obd/socket/SocketServerClient.kt
@@ -1,13 +1,19 @@
package com.flightfeather.obd.socket
import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.DelimiterBasedFrameDecoder
import io.netty.handler.codec.bytes.ByteArrayDecoder
import io.netty.handler.codec.bytes.ByteArrayEncoder
import io.netty.handler.codec.string.StringDecoder
import io.netty.handler.codec.string.StringEncoder
import java.nio.charset.Charset
/**
 * socket长连接服务端
@@ -34,15 +40,18 @@
            return ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel::class.java)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(object : ChannelInitializer<NioSocketChannel>() {
                        override fun initChannel(p0: NioSocketChannel?) {
                            p0?.pipeline()
                                    ?.addLast(StringDecoder())
//                                    ?.addLast("decoder", StringDecoder())
                                    ?.addLast(ObdByteDataDecoder())
                                    ?.addLast("encoder", StringEncoder(Charset.forName("UTF-8")))
                                    ?.addLast(ServerHandler())
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
        } catch (e: Throwable) {
            e.printStackTrace()
        }