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. JS中的Undefined和Null的区别

    Undefined ①在声明变量时,如果没有给变量赋值,则这个变量就是undefined类型: ②访问未声明的变量会报错误消息,但这样的变量使用 typeof 测试,返回的值为Undefined. 即 ...

  2. android自定义View的绘制原理

    每天我们都会使用很多的应用程序,尽管他们有不同的约定,但大多数应用的设计是非常相似的.这就是为什么许多客户要求使用一些其他应用程序没有的设计,使得应用程序显得独特和不同. 如果功能布局要求非常定制化, ...

  3. tms320dm6446内核启动分析

    关于达芬奇DM6446,里面内部有两个部分,一个是ARM926ejs的核,还有一个是C64+DSP的视频处理核,而我需要关心的重点是arm926ejs的核(bootload和linux内核) 从boo ...

  4. bootstrap 幻灯大图结合dedecms的autoindex

    <div class="container" id="banner"> <div id="carousel-example-gene ...

  5. Maven入门(含实例教程)

    原文地址:http://blog.csdn.net/u013142781/article/details/50316383 Maven这个个项目管理和构建自动化工具,越来越多的开发人员使用它来管理项目 ...

  6. 运行项目Tomcat报错

    1.具体报错如下: Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the serve ...

  7. Caused by: java.io.FileNotFoundException

    1.错误描述 usage: java org.apache.catalina.startup.Catalina [ -config {pathname} ] [ -nonaming ] { -help ...

  8. CF368 D - Persistent Bookcase

    re了20多发 还是我在测试数据上操作最后了10多发才发现的 其实只需要多加一句就好了 真的愚蠢啊,要不都能进前100了 #include<bits/stdc++.h> using nam ...

  9. hdu2262 Where is the canteen

    Where is the canteen Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Ot ...

  10. 关于js中 toFixed()的一个小坑

    作为一名前端,大家都应该知道,toFixed()的作用,toFixed()经常用于前台与后台数据格式的转换,套用下w3c上面的定义: 定义和用法toFixed(n) 方法可把 Number 四舍五入为 ...