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. Visual Studio 环境路径答疑!

    工程目录结构如下: Console │ Console.sln │ Console.VC.db │ ├─Console │ │ Console.cpp │ │ Console.vcxproj │ │ ...

  2. 你不知道的JavaScript之类型

    JavaScript是一门简单易用的语言,应用广泛,同时它的语言机制又十分复杂和微妙,即使经验丰富的开发人员也需要用心学习才能真正掌握. <你不知道的JavaScript>中是这样定义类型 ...

  3. java网络编程(2)——UDP与TCP

    首先,先介绍这两种协议: UDP:UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议,是OSI(Open System Interconnection,开放式系统互 ...

  4. linux链接

    ( 1 )软连接可以跨文件系统,硬连接不可以 ( 2 )硬连接不管有多少个,都指向的是同一个 I 节点,会把结点连接数增加,只要结点的连接数不是 0 ,文件就一直存在不管你删除的是源文件还是连接的文件 ...

  5. 在Hadoop2.2基础上安装Spark(伪分布式)

    没想到,在我的hadoop2.2.0小集群上上安装传说中的Spark竟然如此顺利,可能是因为和搭建Hadoop时比较像,更多需要学习的地方还是scala编程和RDD机制吧 总之,开个好头 原来的集群: ...

  6. 让UltraEdit成为java编译器

      1. ?        配置命令: 选择[高级]->[工具栏配置] ?        选择插入按钮进行命令添加: ?        依次填写命令内容: 解释:菜单项目名称:命令的名字,建议使 ...

  7. vxworks下文件读写示例

    dev 1.create file on floopy disk and write contents: -> pdev=fdDevCreate(0,0,0,0)     /* A:,1.44M ...

  8. Java之indexOf()方法

    Java之indexOf()方法 1.方法介绍 (1)indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引 (2)indexOf(String str) 返回指定子字符串在此字符 ...

  9. HighCharts之2D对数饼图

    HighCharts之2D对数饼图 1.实例源码 LogarithmicPie.html: <!DOCTYPE html> <html> <head> <me ...

  10. [2015-06-10 20:53:50 - Android SDK] Error when loading the SDK:

    1.错误描述 [2015-06-10 20:53:50 - Android SDK] Error when loading the SDK: Error: Error parsing D:\Andro ...