NetworkManager

Netty channel wrapper: sendPacket/dispatchPacket, MessageSerializer pipeline, per-connection state machine driver.

net/minecraft/network/NetworkManager.java

Updated 2026-09-12

Packets Referenced (0)

Deep Analysis

Netty-based transport for all Minecraft connections, extending SimpleChannelInboundHandler<Packet>. Owns the Channel, packet listener (INetHandler), and queued outbound packets with read/write locks. Handles connection-state switching, encryption, compression, and local vs TCP channels. Client and server both pump it via processReceivedPackets and sendPacket.

Key Methods (9)

channelRead0

Inbound entry point that dispatches received Packet to current INetHandler.

Checks channel open then calls processPacket(packetListener). Swallows ThreadQuickExitException used to abort handling. All play/login/status packets flow through here.

sendPacket

Queues or immediately dispatches an outbound packet.

If channel open, flushes queue then dispatchPacket; else buffers under write lock. Overload accepts Netty future listeners. Used for every serverbound and clientbound send.

dispatchPacket

Writes packet to channel, handling protocol switches and threading.

Compares EnumConnectionState from packet vs channel attr; disables auto-read on change. If on event loop writes directly, else schedules task. Adds failure listener.

flushOutboundQueue

Drains buffered packets queued before channel was open.

Takes read lock and polls outboundPacketsQueue calling dispatchPacket. Called from sendPacket and processReceivedPackets. Ensures login/handshake ordering.

processReceivedPackets

Per-tick pump for network and packet listener logic.

Flushes outbound queue, ticks packetListener if ITickable, then flushes channel. Called by client runTick and server loops.

setConnectionState

Sets protocol state attribute controlling codec routing.

Stores EnumConnectionState in channel attr and enables auto-read. Called on channelActive as HANDSHAKING and on protocol upgrade during dispatch.

createNetworkManagerAndConnect

Builds client TCP pipeline and connects to remote server.

Selects NIO or Epoll channel, installs timeout/splitter/decoder/prepender/encoder/handler. Uses CLIENTBOUND decoder and SERVERBOUND encoder.

enableEncryption

Inserts cipher codecs for encrypted session after login key exchange.

Adds decrypt before splitter and encrypt before prepender using CryptManager ciphers. Sets isEncrypted flag. Triggered after login encryption response.

setCompressionTreshold

Enables or disables Netty compression codecs dynamically.

Adds NettyCompressionDecoder/Encoder before decoder/encoder if threshold >=0, else removes them. Mirrors login compression negotiation.

Internal State

channelActive Netty channel carrying encoded packets
packetListenerINetHandler receiving decoded packets via channelRead0
outboundPacketsQueueBuffer for sends before channel open, drained in order
directionCLIENTBOUND or SERVERBOUND expected flow for this endpoint
terminationReasonDisconnect message surfaced via getExitMessage

Related Vanilla Internals

Full Source

NetworkManager.java525 lines · MCP 1.8.9 · verbatimOriginal ↗
1
package net.minecraft.network;
2
3
import com.google.common.collect.Queues;
4
import com.google.common.util.concurrent.ThreadFactoryBuilder;
5
import io.netty.bootstrap.Bootstrap;
6
import io.netty.channel.Channel;
7
import io.netty.channel.ChannelException;
8
import io.netty.channel.ChannelFuture;
9
import io.netty.channel.ChannelFutureListener;
10
import io.netty.channel.ChannelHandler;
11
import io.netty.channel.ChannelHandlerContext;
12
import io.netty.channel.ChannelInitializer;
13
import io.netty.channel.ChannelOption;
14
import io.netty.channel.EventLoopGroup;
15
import io.netty.channel.SimpleChannelInboundHandler;
16
import io.netty.channel.epoll.Epoll;
17
import io.netty.channel.epoll.EpollEventLoopGroup;
18
import io.netty.channel.epoll.EpollSocketChannel;
19
import io.netty.channel.local.LocalChannel;
20
import io.netty.channel.local.LocalEventLoopGroup;
21
import io.netty.channel.local.LocalServerChannel;
22
import io.netty.channel.nio.NioEventLoopGroup;
23
import io.netty.channel.socket.SocketChannel;
24
import io.netty.channel.socket.nio.NioSocketChannel;
25
import io.netty.handler.timeout.ReadTimeoutHandler;
26
import io.netty.handler.timeout.TimeoutException;
27
import io.netty.util.AttributeKey;
28
import io.netty.util.concurrent.Future;
29
import io.netty.util.concurrent.GenericFutureListener;
30
import java.net.InetAddress;
31
import java.net.SocketAddress;
32
import java.util.Queue;
33
import java.util.concurrent.locks.ReentrantReadWriteLock;
34
import javax.crypto.SecretKey;
35
import net.minecraft.util.ChatComponentText;
36
import net.minecraft.util.ChatComponentTranslation;
37
import net.minecraft.util.CryptManager;
38
import net.minecraft.util.IChatComponent;
39
import net.minecraft.util.ITickable;
40
import net.minecraft.util.LazyLoadBase;
41
import net.minecraft.util.MessageDeserializer;
42
import net.minecraft.util.MessageDeserializer2;
43
import net.minecraft.util.MessageSerializer;
44
import net.minecraft.util.MessageSerializer2;
45
import org.apache.commons.lang3.ArrayUtils;
46
import org.apache.commons.lang3.Validate;
47
import org.apache.logging.log4j.LogManager;
48
import org.apache.logging.log4j.Logger;
49
import org.apache.logging.log4j.Marker;
50
import org.apache.logging.log4j.MarkerManager;
51
52
public class NetworkManager extends SimpleChannelInboundHandler<Packet>
53
{
54
    private static final Logger logger = LogManager.getLogger();
55
    public static final Marker logMarkerNetwork = MarkerManager.getMarker("NETWORK");
56
    public static final Marker logMarkerPackets = MarkerManager.getMarker("NETWORK_PACKETS", logMarkerNetwork);
57
    public static final AttributeKey<EnumConnectionState> attrKeyConnectionState = AttributeKey.<EnumConnectionState>valueOf("protocol");
58
    public static final LazyLoadBase<NioEventLoopGroup> CLIENT_NIO_EVENTLOOP = new LazyLoadBase<NioEventLoopGroup>()
59
    {
60
        protected NioEventLoopGroup load()
61
        {
62
            return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build());
63
        }
64
    };
65
    public static final LazyLoadBase<EpollEventLoopGroup> CLIENT_EPOLL_EVENTLOOP = new LazyLoadBase<EpollEventLoopGroup>()
66
    {
67
        protected EpollEventLoopGroup load()
68
        {
69
            return new EpollEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Epoll Client IO #%d").setDaemon(true).build());
70
        }
71
    };
72
    public static final LazyLoadBase<LocalEventLoopGroup> CLIENT_LOCAL_EVENTLOOP = new LazyLoadBase<LocalEventLoopGroup>()
73
    {
74
        protected LocalEventLoopGroup load()
75
        {
76
            return new LocalEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Local Client IO #%d").setDaemon(true).build());
77
        }
78
    };
79
    private final EnumPacketDirection direction;
80
    private final Queue<NetworkManager.InboundHandlerTuplePacketListener> outboundPacketsQueue = Queues.<NetworkManager.InboundHandlerTuplePacketListener>newConcurrentLinkedQueue();
81
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
82
83
    /** The active channel */
84
    private Channel channel;
85
86
    /** The address of the remote party */
87
    private SocketAddress socketAddress;
88
89
    /** The INetHandler instance responsible for processing received packets */
90
    private INetHandler packetListener;
91
92
    /** A String indicating why the network has shutdown. */
93
    private IChatComponent terminationReason;
94
    private boolean isEncrypted;
95
    private boolean disconnected;
96
97
    public NetworkManager(EnumPacketDirection packetDirection)
98
    {
99
        this.direction = packetDirection;
100
    }
101
102
    public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception
103
    {
104
        super.channelActive(p_channelActive_1_);
105
        this.channel = p_channelActive_1_.channel();
106
        this.socketAddress = this.channel.remoteAddress();
107
108
        try
109
        {
110
            this.setConnectionState(EnumConnectionState.HANDSHAKING);
111
        }
112
        catch (Throwable throwable)
113
        {
114
            logger.fatal((Object)throwable);
115
        }
116
    }
117
118
    /**
119
     * Sets the new connection state and registers which packets this channel may send and receive
120
     */
121
    public void setConnectionState(EnumConnectionState newState)
122
    {
123
        this.channel.attr(attrKeyConnectionState).set(newState);
124
        this.channel.config().setAutoRead(true);
125
        logger.debug("Enabled auto read");
126
    }
127
128
    public void channelInactive(ChannelHandlerContext p_channelInactive_1_) throws Exception
129
    {
130
        this.closeChannel(new ChatComponentTranslation("disconnect.endOfStream", new Object[0]));
131
    }
132
133
    public void exceptionCaught(ChannelHandlerContext p_exceptionCaught_1_, Throwable p_exceptionCaught_2_) throws Exception
134
    {
135
        ChatComponentTranslation chatcomponenttranslation;
136
137
        if (p_exceptionCaught_2_ instanceof TimeoutException)
138
        {
139
            chatcomponenttranslation = new ChatComponentTranslation("disconnect.timeout", new Object[0]);
140
        }
141
        else
142
        {
143
            chatcomponenttranslation = new ChatComponentTranslation("disconnect.genericReason", new Object[] {"Internal Exception: " + p_exceptionCaught_2_});
144
        }
145
146
        this.closeChannel(chatcomponenttranslation);
147
    }
148
149
    protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, Packet p_channelRead0_2_) throws Exception
150
    {
151
        if (this.channel.isOpen())
152
        {
153
            try
154
            {
155
                p_channelRead0_2_.processPacket(this.packetListener);
156
            }
157
            catch (ThreadQuickExitException var4)
158
            {
159
                ;
160
            }
161
        }
162
    }
163
164
    /**
165
     * Sets the NetHandler for this NetworkManager, no checks are made if this handler is suitable for the particular
166
     * connection state (protocol)
167
     */
168
    public void setNetHandler(INetHandler handler)
169
    {
170
        Validate.notNull(handler, "packetListener", new Object[0]);
171
        logger.debug("Set listener of {} to {}", new Object[] {this, handler});
172
        this.packetListener = handler;
173
    }
174
175
    public void sendPacket(Packet packetIn)
176
    {
177
        if (this.isChannelOpen())
178
        {
179
            this.flushOutboundQueue();
180
            this.dispatchPacket(packetIn, (GenericFutureListener <? extends Future <? super Void >> [])null);
181
        }
182
        else
183
        {
184
            this.readWriteLock.writeLock().lock();
185
186
            try
187
            {
188
                this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])null));
189
            }
190
            finally
191
            {
192
                this.readWriteLock.writeLock().unlock();
193
            }
194
        }
195
    }
196
197
    public void sendPacket(Packet packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners)
198
    {
199
        if (this.isChannelOpen())
200
        {
201
            this.flushOutboundQueue();
202
            this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener));
203
        }
204
        else
205
        {
206
            this.readWriteLock.writeLock().lock();
207
208
            try
209
            {
210
                this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)));
211
            }
212
            finally
213
            {
214
                this.readWriteLock.writeLock().unlock();
215
            }
216
        }
217
    }
218
219
    /**
220
     * Will commit the packet to the channel. If the current thread 'owns' the channel it will write and flush the
221
     * packet, otherwise it will add a task for the channel eventloop thread to do that.
222
     */
223
    private void dispatchPacket(final Packet inPacket, final GenericFutureListener <? extends Future <? super Void >> [] futureListeners)
224
    {
225
        final EnumConnectionState enumconnectionstate = EnumConnectionState.getFromPacket(inPacket);
226
        final EnumConnectionState enumconnectionstate1 = (EnumConnectionState)this.channel.attr(attrKeyConnectionState).get();
227
228
        if (enumconnectionstate1 != enumconnectionstate)
229
        {
230
            logger.debug("Disabled auto read");
231
            this.channel.config().setAutoRead(false);
232
        }
233
234
        if (this.channel.eventLoop().inEventLoop())
235
        {
236
            if (enumconnectionstate != enumconnectionstate1)
237
            {
238
                this.setConnectionState(enumconnectionstate);
239
            }
240
241
            ChannelFuture channelfuture = this.channel.writeAndFlush(inPacket);
242
243
            if (futureListeners != null)
244
            {
245
                channelfuture.addListeners(futureListeners);
246
            }
247
248
            channelfuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
249
        }
250
        else
251
        {
252
            this.channel.eventLoop().execute(new Runnable()
253
            {
254
                public void run()
255
                {
256
                    if (enumconnectionstate != enumconnectionstate1)
257
                    {
258
                        NetworkManager.this.setConnectionState(enumconnectionstate);
259
                    }
260
261
                    ChannelFuture channelfuture1 = NetworkManager.this.channel.writeAndFlush(inPacket);
262
263
                    if (futureListeners != null)
264
                    {
265
                        channelfuture1.addListeners(futureListeners);
266
                    }
267
268
                    channelfuture1.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
269
                }
270
            });
271
        }
272
    }
273
274
    /**
275
     * Will iterate through the outboundPacketQueue and dispatch all Packets
276
     */
277
    private void flushOutboundQueue()
278
    {
279
        if (this.channel != null && this.channel.isOpen())
280
        {
281
            this.readWriteLock.readLock().lock();
282
283
            try
284
            {
285
                while (!this.outboundPacketsQueue.isEmpty())
286
                {
287
                    NetworkManager.InboundHandlerTuplePacketListener networkmanager$inboundhandlertuplepacketlistener = (NetworkManager.InboundHandlerTuplePacketListener)this.outboundPacketsQueue.poll();
288
                    this.dispatchPacket(networkmanager$inboundhandlertuplepacketlistener.packet, networkmanager$inboundhandlertuplepacketlistener.futureListeners);
289
                }
290
            }
291
            finally
292
            {
293
                this.readWriteLock.readLock().unlock();
294
            }
295
        }
296
    }
297
298
    /**
299
     * Checks timeouts and processes all packets received
300
     */
301
    public void processReceivedPackets()
302
    {
303
        this.flushOutboundQueue();
304
305
        if (this.packetListener instanceof ITickable)
306
        {
307
            ((ITickable)this.packetListener).update();
308
        }
309
310
        this.channel.flush();
311
    }
312
313
    /**
314
     * Returns the socket address of the remote side. Server-only.
315
     */
316
    public SocketAddress getRemoteAddress()
317
    {
318
        return this.socketAddress;
319
    }
320
321
    /**
322
     * Closes the channel, the parameter can be used for an exit message (not certain how it gets sent)
323
     */
324
    public void closeChannel(IChatComponent message)
325
    {
326
        if (this.channel.isOpen())
327
        {
328
            this.channel.close().awaitUninterruptibly();
329
            this.terminationReason = message;
330
        }
331
    }
332
333
    /**
334
     * True if this NetworkManager uses a memory connection (single player game). False may imply both an active TCP
335
     * connection or simply no active connection at all
336
     */
337
    public boolean isLocalChannel()
338
    {
339
        return this.channel instanceof LocalChannel || this.channel instanceof LocalServerChannel;
340
    }
341
342
    /**
343
     * Create a new NetworkManager from the server host and connect it to the server
344
     *  
345
     * @param address The address of the server
346
     * @param serverPort The server port
347
     * @param useNativeTransport True if the client use the native transport system
348
     */
349
    public static NetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort, boolean useNativeTransport)
350
    {
351
        final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
352
        Class <? extends SocketChannel > oclass;
353
        LazyLoadBase <? extends EventLoopGroup > lazyloadbase;
354
355
        if (Epoll.isAvailable() && useNativeTransport)
356
        {
357
            oclass = EpollSocketChannel.class;
358
            lazyloadbase = CLIENT_EPOLL_EVENTLOOP;
359
        }
360
        else
361
        {
362
            oclass = NioSocketChannel.class;
363
            lazyloadbase = CLIENT_NIO_EVENTLOOP;
364
        }
365
366
        ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
367
        {
368
            protected void initChannel(Channel p_initChannel_1_) throws Exception
369
            {
370
                try
371
                {
372
                    p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
373
                }
374
                catch (ChannelException var3)
375
                {
376
                    ;
377
                }
378
379
                p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
380
            }
381
        })).channel(oclass)).connect(address, serverPort).syncUninterruptibly();
382
        return networkmanager;
383
    }
384
385
    /**
386
     * Prepares a clientside NetworkManager: establishes a connection to the socket supplied and configures the channel
387
     * pipeline. Returns the newly created instance.
388
     */
389
    public static NetworkManager provideLocalClient(SocketAddress address)
390
    {
391
        final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
392
        ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)CLIENT_LOCAL_EVENTLOOP.getValue())).handler(new ChannelInitializer<Channel>()
393
        {
394
            protected void initChannel(Channel p_initChannel_1_) throws Exception
395
            {
396
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
397
            }
398
        })).channel(LocalChannel.class)).connect(address).syncUninterruptibly();
399
        return networkmanager;
400
    }
401
402
    /**
403
     * Adds an encoder+decoder to the channel pipeline. The parameter is the secret key used for encrypted communication
404
     */
405
    public void enableEncryption(SecretKey key)
406
    {
407
        this.isEncrypted = true;
408
        this.channel.pipeline().addBefore("splitter", "decrypt", new NettyEncryptingDecoder(CryptManager.createNetCipherInstance(2, key)));
409
        this.channel.pipeline().addBefore("prepender", "encrypt", new NettyEncryptingEncoder(CryptManager.createNetCipherInstance(1, key)));
410
    }
411
412
    public boolean getIsencrypted()
413
    {
414
        return this.isEncrypted;
415
    }
416
417
    /**
418
     * Returns true if this NetworkManager has an active channel, false otherwise
419
     */
420
    public boolean isChannelOpen()
421
    {
422
        return this.channel != null && this.channel.isOpen();
423
    }
424
425
    public boolean hasNoChannel()
426
    {
427
        return this.channel == null;
428
    }
429
430
    /**
431
     * Gets the current handler for processing packets
432
     */
433
    public INetHandler getNetHandler()
434
    {
435
        return this.packetListener;
436
    }
437
438
    /**
439
     * If this channel is closed, returns the exit message, null otherwise.
440
     */
441
    public IChatComponent getExitMessage()
442
    {
443
        return this.terminationReason;
444
    }
445
446
    /**
447
     * Switches the channel to manual reading modus
448
     */
449
    public void disableAutoRead()
450
    {
451
        this.channel.config().setAutoRead(false);
452
    }
453
454
    public void setCompressionTreshold(int treshold)
455
    {
456
        if (treshold >= 0)
457
        {
458
            if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder)
459
            {
460
                ((NettyCompressionDecoder)this.channel.pipeline().get("decompress")).setCompressionTreshold(treshold);
461
            }
462
            else
463
            {
464
                this.channel.pipeline().addBefore("decoder", "decompress", new NettyCompressionDecoder(treshold));
465
            }
466
467
            if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder)
468
            {
469
                ((NettyCompressionEncoder)this.channel.pipeline().get("decompress")).setCompressionTreshold(treshold);
470
            }
471
            else
472
            {
473
                this.channel.pipeline().addBefore("encoder", "compress", new NettyCompressionEncoder(treshold));
474
            }
475
        }
476
        else
477
        {
478
            if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder)
479
            {
480
                this.channel.pipeline().remove("decompress");
481
            }
482
483
            if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder)
484
            {
485
                this.channel.pipeline().remove("compress");
486
            }
487
        }
488
    }
489
490
    public void checkDisconnected()
491
    {
492
        if (this.channel != null && !this.channel.isOpen())
493
        {
494
            if (!this.disconnected)
495
            {
496
                this.disconnected = true;
497
498
                if (this.getExitMessage() != null)
499
                {
500
                    this.getNetHandler().onDisconnect(this.getExitMessage());
501
                }
502
                else if (this.getNetHandler() != null)
503
                {
504
                    this.getNetHandler().onDisconnect(new ChatComponentText("Disconnected"));
505
                }
506
            }
507
            else
508
            {
509
                logger.warn("handleDisconnection() called twice");
510
            }
511
        }
512
    }
513
514
    static class InboundHandlerTuplePacketListener
515
    {
516
        private final Packet packet;
517
        private final GenericFutureListener <? extends Future <? super Void >> [] futureListeners;
518
519
        public InboundHandlerTuplePacketListener(Packet inPacket, GenericFutureListener <? extends Future <? super Void >> ... inFutureListeners)
520
        {
521
            this.packet = inPacket;
522
            this.futureListeners = inFutureListeners;
523
        }
524
    }
525
}

Deobfuscated MCP 1.8.9 source of NetworkManager from Marcelektro/MavenMCP-1.8.9 (net/minecraft/network/NetworkManager.java), stored verbatim.