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

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 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值
  • ¥15 VFP如何使用阿里TTS实现文字转语音?