Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.nus.mazegame.client; /** * * @author gejun */ import com.nus.mazegame.domain.MNodeType; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.bytes.ByteArrayDecoder; import io.netty.handler.codec.bytes.ByteArrayEncoder; import java.net.InetSocketAddress; import java.net.SocketAddress; /** * Keeps sending random data to the specified address. */ public final class GameClient { static final String HOST = System.getProperty("host", "127.0.0.1"); static final int PORT = Integer.parseInt(System.getProperty("port", "8007")); public static Bootstrap b; public static void main(String[] args) throws Exception { init(HOST, PORT, MNodeType.CLIENT); } public static void init(String host, final int port, final String type) throws InterruptedException { init(host, port, type, null); } public static void init(String host, final int port, final String type, SocketAddress localAddr) throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); // Decoders p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4)); p.addLast("bytesDecoder", new ByteArrayDecoder()); // Encoder p.addLast("frameEncoder", new LengthFieldPrepender(4)); p.addLast("bytesEncoder", new ByteArrayEncoder()); p.addLast(GameClientHandler.instance); GameInfo.instance.setType(type); GameInfo.instance.setHostPort(port); } }); // Make the connection attempt. SocketAddress address = new InetSocketAddress(host, port); ChannelFuture f; if (localAddr == null) f = b.connect(address).sync(); else f = b.connect(address, localAddr).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } }