通过jar包创建
一、使用导入jar包形式创建
创建java项目,不要选框架
选择hello world模版方便查看
起名字,选存放路径
选File->Project Structure->Modules,点右侧加好,选第一项找到对应的jar包。jar包的下载地址为netty官网。https://netty.io/
引入jar包后,import还是找不到引用,这时候需要清理缓存,如图。这就完成了jar引用。
二、使用maven和pom导入netty
新建maven项目,选maven-archetype-quickstart
GroupId一般是公司域名简写,ArtifactId是项目名称,Version是版本号
不用操作,直接点下一步
选择存放路径
添加pom信息,可以从maven仓库搜索最新版本的xml,然后刷新maven。https://mvnrepository.com/
最后贴上服务端测试代码,成功运行起来就说明环境搭建好了
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class GameServer {
public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();//线程组
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();//server启动管理配置
b.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)//最大客户端连接数为1024
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//这里我们先不写代码,这里主要是添加业务处理handler
}
});
ChannelFuture f = b.bind(port).sync();
if (f.isSuccess()) {
System.out.println("Server starts success at port:" + port);
}
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
new GameServer().bind(port);
}
}