使用netty的第一个Hello World
server端
package com.netty.test;
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 DiscardServer {
private static int port = 8080;
private static String tcpIp = "localhost";
public static void run(){
EventLoopGroup bossGroup = new NioEventLoopGroup();//用于处理服务器端,接收客户端链接
EventLoopGroup workerGroup = new NioEventLoopGroup();//进行网络通信(读写)
try {
ServerBootstrap b = new ServerBootstrap();//辅助工具类,用于服务器通道的一系列配置
//绑定两个线程组
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)//指定nio模式
.childHandler(new ChannelInitializer<SocketChannel>() {//配置具体的数据处理方式,处理数据用io模式,该地方使用io包
@Override
protected void initChannel(SocketChannel socketChannel)
throws Exception {
socketChannel.pipeline().addLast(new ServerHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128)//设置tcp缓冲区
.option(ChannelOption.SO_SNDBUF, 32 * 1024) //设置发送数据缓冲区
.option(ChannelOption.SO_RCVBUF, 32 * 1024)//设置接收数据的缓冲区
.childOption(ChannelOption.SO_KEEPALIVE, true);//保持链接
//绑定端口
ChannelFuture future = b.bind(tcpIp, port).sync()/*b.bind(port).sync()*/;
future.channel().closeFuture().sync();
} catch (Exception e) {
System.out.println("产生了异常;异常是" + e.getMessage());
}finally{
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
run();
}
}
ServerHandler类
package com.netty.test;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/*
* 服务器接收和返回数据
*/
public class ServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 接收客户端的消息
ByteBuf buf = (ByteBuf)msg;
byte[] data = new byte[buf.readableBytes()];
buf.readBytes(data);
String request = new String(data, "utf-8");
System.out.println("Server: " + request);
// 写给客户端
ctx.writeAndFlush(Unpooled.copiedBuffer("888".getBytes()));
//.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
Client端
package com.netty.test;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/*
* 客户端
*/
public class Client {
private static int port = 8080;
private static String tcpIp = "localhost";
public static void main(String[] args) {
EventLoopGroup worGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(worGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ClientHandler());
}
});
try {
ChannelFuture future = bootstrap.connect(tcpIp, port).sync();
// 给服务器发送消息
future.channel().writeAndFlush(Unpooled.copiedBuffer("Hello World!".getBytes()));
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
System.out.println("绑定ip和端口时抛出异常,异常是" + e.getMessage());
e.printStackTrace();
} finally {
worGroup.shutdownGracefully();
}
}
}
ClientHandler类
package com.netty.test;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
/*
* 接收服务器返回的消息
*/
public class ClientHandler extends ChannelInboundHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
try {
ByteBuf buf = (ByteBuf)msg;
byte[] data = new byte[buf.readableBytes()];
buf.readBytes(data);
System.out.println("Client : " + new String(data).trim());
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
使用netty的第一个Hello World的更多相关文章
- Netty实现的一个异步Socket代码
本人写的一个使用Netty实现的一个异步Socket代码 package test.core.nio; import com.google.common.util.concurrent.ThreadF ...
- Netty(1):第一个netty程序
为什么选择Netty netty是业界最流行的NIO框架之一,它的健壮型,功能,性能,可定制性和可扩展性都是首屈一指的,Hadoop的RPC框架Avro就使用了netty作为底层的通信框架,此外net ...
- 【Netty】第一个Netty应用
一.前言 前面已经学习完了Java NIO的内容,接着来学习Netty,本篇将通过一个简单的应用来了解Netty的使用. 二.Netty应用 2.1 服务端客户端框架图 下图展示了Netty中服务端与 ...
- Netty 4 实现一个 NettyClient
本文章为作者原创,有问题的地方请提出指正. 1.类继承Diagram 2.定义EndPoint类 目前仅仅定义了2个方法,分别用来获取本地或远程服务器的地址. package netty; impor ...
- java使用netty模拟实现一个类dubbo的分布式服务调用框架
本文较长,如果想直接看代码可以查看项目源码地址: https://github.com/hetutu5238/rpc-demo.git 要想实现分布式服务调用框架,我们需要了解分布式服务一般需要的功能 ...
- netty系列之:一个价值上亿的网站速度优化方案
目录 简介 本文的目标 支持多个图片服务 http2处理器 处理页面和图像 价值上亿的速度优化方案 总结 简介 其实软件界最赚钱的不是写代码的,写代码的只能叫马龙,高级点的叫做程序员,都是苦力活.那么 ...
- netty(二) 创建一个netty服务端和客户端
服务端 NettyServer package com.zw.netty.config; import com.zw.netty.channel.ServerInitializer;import io ...
- Netty+SpringBoot写一个基于Http协议的文件服务器
本文参考<Netty权威指南> NettyApplication package com.xh.netty; import org.springframework.boot.SpringA ...
- 使用Netty实现的一个简单HTTP服务器
1.HttpServer,Http服务启动类,用于初始化各种线程和通道 public class HttpServer { public void bind(int port) throws Exce ...
随机推荐
- Log4j与Log4j2
完整的软件,日志是必不可少的.程序从开发.测试.维护.运行等环节,都需要向控制台或文件等位置输出大量信息.这些信息的输出,在很多时候是System.out.println()无法完成日志信息根据用途与 ...
- opencv 离线文档下载地址在哪里?
OpenCV 官方离线文档下载地址:http://docs.opencv.org/ 如何生成离线文档? http://docs.opencv.org/master/d4/db1/tutorial_do ...
- IntentService源码
原文地址IntentService源码分析 @Override public void onCreate() { super.onCreate(); HandlerThread thread = ne ...
- Git & github 使用指南
Git的安装: 1.下载 Git for windows下载网址:https://git-for-windows.github.io/ 2.安装 选择安装路径: 选择组件:默认 是否修改环境变量 : ...
- javascript学习笔记02--面向对象学习
js面向对象编程 1. javascript 是一种基于对象的编程 object-based(基于对象):遇到的所有对象都是对象2.javascript没有类class,但是有新的原型对象,习 ...
- CSS3之Border-radius
1.属性介绍 border-radius:none|12.3px,取值不可为负数,表示边框圆角 相关属性:border-top-right-radius , border-bottom-right-r ...
- Java求素数时出现错误
Java求素数时出现错误 1.具体错误如下 No enclosing instance of type Prime is accessible. Must qualify the allocation ...
- axure 7.0 注册码
Axure RP 7.0注册码: 用户名:axureuser 序列号:8wFfIX7a8hHq6yAy6T8zCz5R0NBKeVxo9IKu+kgKh79FL6IyPD6lK7G6+tqEV4LG ...
- Count:858org.apache.jasper.JasperException: Unable to compile class for JSP
1.错误描述 Count:858org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurre ...
- ubuntu14.04 64位 安装Tomcat
ubuntu14.04 64位 安装Tomcat 1 下载Tomcat 在htt://www.tomcat.apache.org官网上下载apache-tomcat-7.0.57.tar.gz 2 解 ...