Cc_Davis_cC 2016-08-10 02:34 采纳率: 0%
浏览 2213
已结题

netty5.0客户端发送消息,服务器端接收失败

package com.vc.netty.simplechat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SimpleChatClient {
public static void main(String[] args) throws Exception{
new SimpleChatClient("127.0.0.1", 9833).run();
}

    private final String host;
    private final int port;

    public SimpleChatClient(String host, int port){
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap  = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new SimpleChatClientInitializer());
            Channel channel = bootstrap.connect(host, port).sync().channel();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("["+in.readLine()+"]");
            while(true){
                channel.writeAndFlush(in.readLine() + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }
}

以上是客户端代码。


/**

  • @author vc DateTime 2015年3月30日 下午2:06:01
  • @version 1.0 */ package com.vc.netty.simplechat.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class SimpleChatClientHandler extends SimpleChannelInboundHandler {
// @Override
// protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
// System.out.println(s);
// }
/*@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
System.out.println(ctx.toString());
System.out.println(obj.toString());
};*/

@Override
protected void messageReceived(ChannelHandlerContext ctx, String msg)
        throws Exception {
    System.out.println(msg);

}

}
以上是clientHandler代码


package com.vc.netty.simplechat.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class SimpleChatServer {

private int port;

public SimpleChatServer(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 SimpleChatServerInitializer())  //(4)
         .option(ChannelOption.SO_BACKLOG, 128)          // (5)
         .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        System.out.println("SimpleChatServer 启动了");

        // 绑定端口,开始接收进来的连接
        ChannelFuture f = b.bind(port).sync(); // (7)

        // 等待服务器  socket 关闭 。
        // 在这个例子中,这不会发生,但你可以优雅地关闭你的服务器。
        f.channel().closeFuture().sync();

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

        System.out.println("SimpleChatServer 关闭了");
    }
}

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

}

}
以上是服务器端代码


package com.vc.netty.simplechat.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class SimpleChatServerHandler extends SimpleChannelInboundHandler { // (1)

public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {  // (2)
    Channel incoming = ctx.channel();
    for (Channel channel : channels) {
        channel.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 加入\n");
    }
    channels.add(ctx.channel());
}

@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {  // (3)
    Channel incoming = ctx.channel();
    for (Channel channel : channels) {
        channel.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 离开\n");
    }
    channels.remove(ctx.channel());
}

// @Override
// protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception { // (4)
// Channel incoming = ctx.channel();
// for (Channel channel : channels) {
// if (channel != incoming){
// channel.writeAndFlush("[" + incoming.remoteAddress() + "]" + s + "\n");
// } else {
// channel.writeAndFlush("[you]" + s + "\n");
// }
// }
// }

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
    Channel incoming = ctx.channel();
    System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"在线");
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
    Channel incoming = ctx.channel();
    System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"掉线");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
    Channel incoming = ctx.channel();
    System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"异常");
    // 当出现异常就关闭连接
    cause.printStackTrace();
    ctx.close();
}

@Override
protected void messageReceived(ChannelHandlerContext ctx, String msg)
        throws Exception {
    Channel incoming = ctx.channel();
    for (Channel channel : channels) {
        if (channel != incoming){
            channel.writeAndFlush("[" + incoming.remoteAddress() + "]" + msg + "\n");
        } else {
            channel.writeAndFlush("[you]" + msg + "\n");
        }
    }

}

}
以上是serverHandler代码


  • 写回答

1条回答 默认 最新

  • dabocaiqq 2017-03-03 21:36
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题