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的更多相关文章

  1. Netty实现的一个异步Socket代码

    本人写的一个使用Netty实现的一个异步Socket代码 package test.core.nio; import com.google.common.util.concurrent.ThreadF ...

  2. Netty(1):第一个netty程序

    为什么选择Netty netty是业界最流行的NIO框架之一,它的健壮型,功能,性能,可定制性和可扩展性都是首屈一指的,Hadoop的RPC框架Avro就使用了netty作为底层的通信框架,此外net ...

  3. 【Netty】第一个Netty应用

    一.前言 前面已经学习完了Java NIO的内容,接着来学习Netty,本篇将通过一个简单的应用来了解Netty的使用. 二.Netty应用 2.1 服务端客户端框架图 下图展示了Netty中服务端与 ...

  4. Netty 4 实现一个 NettyClient

    本文章为作者原创,有问题的地方请提出指正. 1.类继承Diagram 2.定义EndPoint类 目前仅仅定义了2个方法,分别用来获取本地或远程服务器的地址. package netty; impor ...

  5. java使用netty模拟实现一个类dubbo的分布式服务调用框架

    本文较长,如果想直接看代码可以查看项目源码地址: https://github.com/hetutu5238/rpc-demo.git 要想实现分布式服务调用框架,我们需要了解分布式服务一般需要的功能 ...

  6. netty系列之:一个价值上亿的网站速度优化方案

    目录 简介 本文的目标 支持多个图片服务 http2处理器 处理页面和图像 价值上亿的速度优化方案 总结 简介 其实软件界最赚钱的不是写代码的,写代码的只能叫马龙,高级点的叫做程序员,都是苦力活.那么 ...

  7. netty(二) 创建一个netty服务端和客户端

    服务端 NettyServer package com.zw.netty.config; import com.zw.netty.channel.ServerInitializer;import io ...

  8. Netty+SpringBoot写一个基于Http协议的文件服务器

    本文参考<Netty权威指南> NettyApplication package com.xh.netty; import org.springframework.boot.SpringA ...

  9. 使用Netty实现的一个简单HTTP服务器

    1.HttpServer,Http服务启动类,用于初始化各种线程和通道 public class HttpServer { public void bind(int port) throws Exce ...

随机推荐

  1. QWebSocket 客户端

    QWebSocket 客户端 Public Function - QWebSocket(const QString &origin = QString(),QWebSocketProtocol ...

  2. the c programing language 学习过程4

    4Functions and Program Structure scratch 刮擦 starting over from scratch从头开始 reside驻留 separately 分别的 f ...

  3. 求指定区间内与n互素的数的个数 容斥原理

    题意:给定整数n和r,求区间[1, r]中与n互素的数的个数. 详细见容斥定理 详细代码如下 int solve(int r, int n) { vector<int>p; p.clear ...

  4. nyoj 1129 Salvation 模拟

    思路:每个坐标有四种状态,每个点对应的每种状态只能走一个方向,如果走到一个重复的状态说明根本不能走到终点,否则继续走即可. 坑点:有可能初始坐标四周都是墙壁,如果不判断下可能会陷入是死循环. 贴上测试 ...

  5. UVA - 1218 Perfect Service (树形DP)

    思路:dp[i][0]表示i是服务器:dp[i][1]表示i不是服务器,但它的父节点是服务器:dp[i][2]表示i和他的父亲都不是服务器.       转移方程: d[u][0] += min(d[ ...

  6. React——diff算法

    react的diff算法基于两个假设: 1.不同类型的元素会产生不同的树 2.通过设置key,开发者能够提示那些子组件是稳定的 diff算法 当比较两个树时,react首先会比较两个根节点,接下来具体 ...

  7. MySQL之pymysql模块

    MySQL之pymysql模块   import pymysql #s链接数据库 conn = pymysql.connect( host = '127.0.0.1', #被连接数据库的ip地址 po ...

  8. ARM-LINUX自动采集温湿度传感器数据

    开机root自动登录 如果想在超级终端输入回车,登录后执行,则可以在/etc/profile中加入命令: 如果实现开机自动登录,在/etc/inittab中修改,每个开发板修改的方式可能都不同. ht ...

  9. FusionCharts封装-单系列图

    ColumnChart.java: /** * @Title:ColumnChart.java * @Package:com.fusionchart.model * @Description:柱形图 ...

  10. 织梦dedecms列表序号从0到1开始的办法 autoindex,itemindex标签

    自增1 arclist            标签下使用 [field:global.autoindex/] 默认从1开始 channel         标签下使用 [field:global.au ...