一般的请求都是从客户端发起请求到服务端,服务端接收到请求后做相应处理然后在返回给客户端相应信息,但是很多时候我们要用服务端作为客户端在发送请求到另一台服务端,这样中的这台服务器不仅是服务端也是客户端。
OK 整体请求就是这样的,下面来看代码:
一、客户端
1、客户端引导
package com.test3;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* 客户端
* @author whd
* @date 2017年9月24日 上午12:26:34
*/
public class Client {
public void start(String host, int port) {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.handler(new InitializerChannel());
ChannelFuture future = bootstrap.connect(host, port).sync();
System.out.println("client started……");
future.channel().closeFuture().sync();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
workerGroup.shutdownGracefully();
}
}
private class InitializerChannel extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ClientHandler());
}
}
public static void main(String[] args) {
String ip = "127.0.0.1";
int port = 8080;
if (null != args && args.length == 2) {
ip = args[0];
port = Integer.valueOf(args[1]);
}
Client client = new Client();
client.start(ip, port);
}
}
2、客户端处理类
package com.test3;
import java.io.UnsupportedEncodingException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* 客户端对请求响应事件的处理
*
* @author whd
* @date 2017年9月24日 上午12:27:22
*/
public class ClientHandler extends ChannelHandlerAdapter {
private static final String CHAR_SET = "UTF-8";
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf buf = string2Buf("client active");
// 在channelactive中一定要记得flush
ctx.writeAndFlush(buf);
}
// 该channel有读事件发生时触发该方法
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
String body = buf2String(buf);
System.out.println(body);
}
// 当读事件结束后触发该方法
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();// 将消息发送队列中的消息写入到SocketChannel中发送给对方。
ctx.close();
}
// 出现异常触发该方法
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
/**
* @param buf
* @return
* @throws UnsupportedEncodingException
*/
private String buf2String(ByteBuf buf) throws UnsupportedEncodingException {
if (null == buf) {
return null;
}
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String str = new String(bytes, ClientHandler.CHAR_SET);
return str;
}
private ByteBuf string2Buf(String msg) throws UnsupportedEncodingException {
if (null == msg) {
return null;
}
byte[] bytes = msg.getBytes(ClientHandler.CHAR_SET);
ByteBuf buf = Unpooled.buffer(bytes.length);
buf.writeBytes(bytes);
return buf;
}
}
二、服务端-客户端
1、服务端引导
package com.test.cs;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
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 Server {
private void bind(String ip, int serverPort) {
// 服务端线程组
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup work = new NioEventLoopGroup();
ServerBootstrap strap = new ServerBootstrap();
strap.group(boss, work).option(ChannelOption.SO_BACKLOG, 1024).channel(NioServerSocketChannel.class)
.childHandler(new ChannelIniter());
try {
ChannelFuture future = strap.bind(serverPort).sync();
System.out.println("server-client started ……");
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
boss.shutdownGracefully();
work.shutdownGracefully();
}
}
private class ChannelIniter extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
// handler容器
ChannelPipeline cp = sc.pipeline();
// 具体事务处理
cp.addLast(new ServerHandler());
}
}
public static void main(String[] args) {
int serverPort = 8080;
String ip = "127.0.0.1";
Server server = new Server();
server.bind(ip, serverPort);
}
}
2、服务端处理类
package com.test.cs;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* io事件处理,重写需要的方法
*
* @author whd
* @date 2017年11月4日 下午9:56:05
*/
public class ServerHandler extends ChannelHandlerAdapter {
private static final String SERVER_IP="127.0.0.1";
private static final int SERVER_PORT=8081;
private static final String CHAR_SET = "UTF-8";
//读取客户端数据,向客户端返回应答
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
String str = this.buf2String((ByteBuf)msg);
System.out.println("from client info "+str);
this.info();
String time = "server-client time"+new Date(System.currentTimeMillis());
ByteBuf buf = this.string2Buf(time);
ctx.write(buf);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
ctx.close();
}
/**
* 服务端作为客户端向服务端发送请求
*/
private void info() {
Bootstrap strap = new Bootstrap();
EventLoopGroup work = new NioEventLoopGroup();
strap.group(work).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>(){
@Override
public void initChannel(SocketChannel sc){
ChannelPipeline cp = sc.pipeline();
cp.addLast( new ChannelHandlerAdapter(){
//服务端响应事件处理
@Override
public void channelActive(ChannelHandlerContext ctx){
System.out.println("server-client connection success");
String info ="server-client_time"+new Date(System.currentTimeMillis());
try {
ByteBuf buf = Unpooled.copiedBuffer(info.getBytes("utf-8"));
ctx.writeAndFlush(buf);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//从服务端读取数据
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg){
String info = buf2String((ByteBuf)msg);
System.out.println(info);
}
//客户端从服务端读取数据结束
@Override
public void channelReadComplete(ChannelHandlerContext ctx){
ctx.flush();
ctx.close();
}
});
}
});
try {
ChannelFuture future = strap.connect(ServerHandler.SERVER_IP,ServerHandler.SERVER_PORT).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
work.shutdownGracefully();
}finally{
System.out.println("server-client_info_end");
}
}
/**
* @param buf
* @return
*/
private String buf2String(ByteBuf buf){
byte [] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String str = null;
try {
str = new String(bytes,ServerHandler.CHAR_SET);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
/**
*
* @param msg
* @return
* @throws UnsupportedEncodingException
*/
private ByteBuf string2Buf(String msg) throws UnsupportedEncodingException {
if (null == msg) {
return null;
}
byte[] bytes = msg.getBytes(ServerHandler.CHAR_SET);
ByteBuf buf = Unpooled.buffer(bytes.length);
buf.writeBytes(bytes);
return buf;
}
}
三、服务端
1、最终服务端引导
package com.test3;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
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 Server2 {
private void listen(String ip,int port){
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup work = new NioEventLoopGroup();
try{
ServerBootstrap strap = new ServerBootstrap();
strap.group(boss, work).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).childHandler(new InitChannel());
ChannelFuture future = strap.bind(ip, port).sync();
System.out.println("final server started……");
future.channel().closeFuture().sync();
}catch(Exception e){
e.printStackTrace();
boss.shutdownGracefully();
work.shutdownGracefully();
}
}
private static final class InitChannel extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// TODO Auto-generated method stub
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new Server2Handler());
}
}
public static void main(String[] args) {
Server2 server2 = new Server2();
String ip="127.0.0.1";
int port =8081;
server2.listen(ip, port);
}
}
package com.test3;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class Server2Handler extends ChannelHandlerAdapter {
private static final String CHAR_SET="UTF-8";
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
ByteBuf buf = (ByteBuf) msg;
String message = buf2String(buf);
System.out.println(message);
String info = "message from final server"+new Date();
ByteBuf bufInfo = string2Buf(info);
ctx.write(bufInfo);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
ctx.close();
}
/**
* @param buf
* @return
* @throws UnsupportedEncodingException
*/
private String buf2String(ByteBuf buf) throws UnsupportedEncodingException {
if (null == buf) {
return null;
}
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String str = new String(bytes, Server2Handler.CHAR_SET);
return str;
}
private ByteBuf string2Buf(String msg) throws UnsupportedEncodingException {
if (null == msg) {
return null;
}
byte[] bytes = msg.getBytes(Server2Handler.CHAR_SET);
ByteBuf buf = Unpooled.buffer(bytes.length);
buf.writeBytes(bytes);
return buf;
}
}