请问Netty5客户端怎么主动给服务端发消息?

笨鸟先飞_ 2016-04-15 05:36:25
服务端

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 NettyServer {
private int port;

public NettyServer(int port) {
this.port = port;
}

public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyServerHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync(); // (7)

// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to
// gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}

public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new NettyServer(port).run();
}
}

服务端消息处理

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class NettyServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)

//接收
ByteBuf in = (ByteBuf) msg;
try {

System.out.println(in.toString(io.netty.util.CharsetUtil.UTF_8));
// while (in.isReadable()) { // (1)
// System.out.print((char) in.readByte());
// System.out.flush();
// }
} finally {
ReferenceCountUtil.release(msg); // (2)
}
//发送
ctx.write("这是服务端".getBytes(Charset.forName("UTF-8"))); // (1)
ctx.flush(); // (2)
}

@Override
public void channelActive(final ChannelHandlerContext ctx) { // (1)
final ByteBuf buff = ctx.alloc().buffer(64); // (2)
buff.writeBytes("欢迎光临".getBytes(Charset.forName("UTF-8")));

final ChannelFuture f = ctx.writeAndFlush(buff);
f.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
assert f == future;
ctx.close();
}
});
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}

客户端

import io.netty.bootstrap.Bootstrap;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
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.NioSocketChannel;

public class NettyClient {





public static void main(String[] args) throws Exception {
String host = "127.0.0.1";
int port = 8080;
EventLoopGroup workerGroup = new NioEventLoopGroup();

try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyClientHandler());
}
});

// Start the client.
ChannelFuture f = b.connect(host, port).sync(); // (5)

// Wait until the connection is closed.
f.channel().closeFuture().sync();

} finally {
workerGroup.shutdownGracefully();
}
}
}

客户端消息处理


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.nio.charset.Charset;


public class NettyClientHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
//虽然这里可以给服务端发消息但是我想在其他地方需要发消息的时候再发而不是收到服务端发来消息才发
ByteBuf buf = (ByteBuf)msg;
System.out.println(buf.toString(Charset.forName("UTF-8")));
ctx.close();
} finally {
}
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
...全文
2038 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_38881332 2017-08-01
  • 打赏
  • 举报
回复
和socket的区别在哪
紫羽飞刃 2016-10-16
  • 打赏
  • 举报
回复
我也遇到和你同样问题,你解决了吗?
andyweike 2016-08-06
  • 打赏
  • 举报
回复
试试调用 channelFuture.channel().writeAndFlush(); 来主动给服务端发。
zhouqinxiong 2016-05-12
  • 打赏
  • 举报
回复
有结果了吗?
笨鸟先飞_ 2016-04-15
  • 打赏
  • 举报
回复
难道直接socket?

51,397

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧