网状的,米娜,扭曲一起学系列01:实现简单的TCP服务器

网状的,米娜,扭曲一起学系列01:实现简单的TCP服务器

<节>

<节>

<节>

<节>

<节>

<节>

<节>

<节>

<强> event-driven  <强>异步 <强>事件驱动 <强>异步的网络编程框架

<节>
 <代码> {

,InterruptedException {
,,EventLoopGroup bossGroup=NioEventLoopGroup ();
,,EventLoopGroup workerGroup=NioEventLoopGroup ();
,,{
,,,ServerBootstrap b=ServerBootstrap ();
,,b。集团(bossGroup workerGroup)
,,,,,.channel (NioServerSocketChannel.class)
,,,,,。childHandler (ChannelInitializer () {
,,,,,,
,,,,,
,,,,,,,,异常{
,,,,,,,ch.pipeline ()。addLast (TcpServerHandler ());
,,,,,}
大敌;,,,,});
,,.sync, ChannelFuture f=b.bind () ();
,,.sync .closeFuture, f.channel () () ();
,,}{
,,,workerGroup.shutdownGracefully ();
,,,bossGroup.shutdownGracefully ();
,,}
}

}

{

,
,
,UnsupportedEncodingException {
,,{
,,,
,=(ByteBuf)味精,ByteBuf;
,,system . out。println (+ in.toString (CharsetUtil.UTF_8));

,,,
,,[]responseByteArray=.getBytes ();
,,,ByteBuf=ctx.alloc () .buffer (responseByteArray.length);
,,,out.writeBytes (responseByteArray);
,,,ctx.writeAndFlush(出),

,,}{
,,,ReferenceCountUtil.release(味精);
,,}
}

,
,{
,,System.out.println ();
,}

,
,{
,,System.out.println ();
,}

,
,{
,,cause.printStackTrace ();
,,ctx.close ();
,}
}


<节> <节>
 <代码> {

,IOException {
,,IoAcceptor受体=NioSocketAcceptor ();
,承兑人。setHandler (TcpServerHandle ());
,承兑人。绑定(InetSocketAddress ());
,}

}

{

,
,异常{
,,cause.printStackTrace ();
,}

,
,
,异常{

,,
,IoBuffer IoBuffer=(IoBuffer)消息;
,,中byteArray=[] [ioBuffer.limit ());
,ioBuffer。get(中byteArray, ioBuffer.limit ());
,system . out。中byteArray, println(+字符串());

,,
,[]responseByteArray=.getBytes ();
,,IoBuffer responseIoBuffer=IoBuffer.allocate (responseByteArray.length);
,,responseIoBuffer.put (responseByteArray);
,,responseIoBuffer.flip ();
,,session.write (responseIoBuffer);
,}

,
,异常{
,,System.out.println ();
,}

,
,异常{
,,System.out.println ();
,}
}


<节> <节>
 <代码> 

twisted.internet.protocol协议

twisted.internet twisted.internet.protocol工厂反应堆

:

,,
,:
,,,,

,,
,:
,,,,

,,
,:
,,,,、数据
,,,,self.transport.write ()

工厂=工厂()
工厂。协议=TcpServerHandle
反应堆。listenTCP(工厂)
reactor.run()

<节>

<节>
 <代码> {

,IOException InterruptedException {


,,Socket套接字=,
,,OutputStream=,
,,InputStream=,

,,{

,,,套接字=套接字(,);,,null

网状的,米娜,扭曲一起学系列01:实现简单的TCP服务器