一个简单 netty client pojo通讯实现

------------------------------------

1

------------------------------------

package admin.netty;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

public class TimeClientHandler extends SimpleChannelHandler { 
 
    private String returnFlag = null;
   
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        CtrlProtocol m = (CtrlProtocol) e.getMessage();
        this.returnFlag = m.getFlag();
        //System.out.println(returnFlag);
        e.getChannel().close();
    }
 
    @Override 
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {  
        e.getCause().printStackTrace();  
        e.getChannel().close();  
    }      
     
    public ChannelFuture process(Channel channel,CtrlProtocol requestParameter) {
        return channel.write(requestParameter);
    }
   
    public String getReturnFlag(){
        return this.returnFlag;
    }
}

------------------------------- 

2

-------------------------------

package admin.netty;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;

public class TimeClientPipelineFactory implements ChannelPipelineFactory {

    public ChannelPipeline getPipeline() {
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("decoder", new CtrlProtocolDecoder());
        pipeline.addLast("encoder", new CtrlProtocolEncoder());       
        pipeline.addLast("handler", new TimeClientHandler());
        return pipeline;
    }
}

------------------------------- 

3

-------------------------------

package admin.netty;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CtrlProtocolDecoder extends FrameDecoder {

    private static final Log    ilog    = LogFactory.getLog(CtrlProtocolDecoder.class);

    /*
     * (non-Javadoc)
     * @see org.jboss.netty.handler.codec.frame.FrameDecoder#decode(org.jboss.netty.channel.ChannelHandlerContext,
     * org.jboss.netty.channel.Channel, org.jboss.netty.buffer.ChannelBuffer)
     */
    @Override
    protected CtrlProtocol decode(ChannelHandlerContext arg0, Channel arg1, ChannelBuffer arg2) throws Exception {

        ChannelBuffer buf = arg2;

        if (buf.readableBytes() < 8) {
            ilog.error("收到的协议数据不完整,无法解析协议头.");           
            return null;
        }

        short head_flag = buf.readShort();
        short head_code = buf.readShort();
        int head_length = buf.readInt();

        CtrlProtocol protocol = new CtrlProtocol(head_flag, head_code, head_length);
       
        ilog.info("收到的协议:" + head_flag + "    " + head_code + "    " + head_length + "\n");

        return protocol;
    }
}

------------------------------- 

4

-------------------------------

package admin.netty;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

public class CtrlProtocolEncoder extends OneToOneEncoder {

    /*
     * (non-Javadoc)
     * @see org.jboss.netty.handler.codec.oneone.OneToOneEncoder#encode(org.jboss.netty.channel.ChannelHandlerContext,
     * org.jboss.netty.channel.Channel, java.lang.Object)
     */
    @Override
    protected Object encode(ChannelHandlerContext arg0, Channel arg1, Object arg2) throws Exception {
        CtrlProtocol protocol = (CtrlProtocol) arg2;

        ChannelBuffer buf = ChannelBuffers.dynamicBuffer();

        buf.writeShort((short) protocol.getFlag());
        buf.writeShort((short) protocol.getCode());
        buf.writeInt(protocol.getLength());
/*略去*/
        return buf;
    }
}

------------------------------- 

5

-------------------------------

package admin.netty;

public class CtrlProtocol {

    private short            flag        = 0;
    private short            code        = 0;
    private int            length        = 0;

    public CtrlProtocol(short f, short c, int l) {
        flag = f;
        code = c;
        length = l;
    }
   
    public static CtrlProtocol getCtrlInstance() {
        return new CtrlProtocol((short) 1, (short) 1, (short) 1);
    }

    public short getFlag() {

        return flag;
    }

    public void setFlag(short flag) {

        this.flag = flag;
    }

    public short getCode() {

        return code;
    }

    public void setCode(short code) {

        this.code = code;
    }

    public int getLength() {

        return length;
    }

    public void setLength(int length) {

        this.length = length;
    }
  /* 略去*/
}

------------------------------- 

6 客户端执行异步发送接收(服务端返回数据与客户端发送数据结构一致)

-------------------------------

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

....

            CtrlProtocol cp = CtrlProtocol.getCtrlInstance();
....

            String flag = this.toDo (cp);

///

    //Socket异步发送接收通讯协议
    //参数:CtrlProtocol 协议

private String toDo (CtrlProtocol cp) throws Exception{
        String flag = "0";//结果
        String host ="127.0.0.1";

        int port = 7788;


        ChannelFactory factory = new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());

        ClientBootstrap bootstrap = new ClientBootstrap(factory);

        bootstrap.setPipelineFactory(new TimeClientPipelineFactory());

        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setOption("keepAlive", true);
       
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(
                host, port));
        Channel channel = future.awaitUninterruptibly().getChannel();
        TimeClientHandler handler = channel.getPipeline().get(TimeClientHandler.class);
               
        handler.process(channel, cp);       
       
        future.awaitUninterruptibly();
        if (!future.isSuccess()) {
            future.getCause().printStackTrace();
        }       
       
        future.getChannel().getCloseFuture().awaitUninterruptibly();
        factory.releaseExternalResources();
        flag = handler.getReturnFlag();
               
        return flag;
    }

 

 

 

抱歉,作为AI语言模型,我无法编写实际的代码,但是我可以向您提供一些基本的步骤和代码示例,以便您开始编写Netty即时通信Demo。 1. 导入Netty依赖 在您的Maven项目中,将以下依赖项添加到pom.xml文件中: ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.65.Final</version> </dependency> ``` 2. 创建服务器 创建一个Netty服务器来接收客户端连接并处理消息: ``` public class ChatServer { private final int port; public ChatServer(int port) { this.port = port; } public void start() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ChatServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } ``` 3. 创建消息处理器 创建一个消息处理器来处理客户端发送的消息: ``` public class ChatServerHandler extends SimpleChannelInboundHandler<String> { private static final Map<Channel, String> channelMap = new ConcurrentHashMap<>(); private static final String CHAT_SERVER = "ChatServer"; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); String remoteAddress = channel.remoteAddress().toString(); channelMap.put(channel, remoteAddress); System.out.println("Client " + remoteAddress + " connected to " + CHAT_SERVER); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); String remoteAddress = channel.remoteAddress().toString(); channelMap.remove(channel); System.out.println("Client " + remoteAddress + " disconnected from " + CHAT_SERVER); super.channelInactive(ctx); } @Override protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception { Channel channel = ctx.channel(); String remoteAddress = channel.remoteAddress().toString(); System.out.println("Received message from " + remoteAddress + ": " + message); for (Channel ch : channelMap.keySet()) { if (ch != channel) { ch.writeAndFlush("[" + remoteAddress + "]: " + message + "\n"); } } } } ``` 4. 创建客户端 创建一个Netty客户端来连接服务器并发送消息: ``` public class ChatClient { private final String host; private final int port; public ChatClient(String host, int port) { this.host = host; this.port = port; } public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ChatClientHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { String message = in.readLine(); if (message == null) { break; } f.channel().writeAndFlush(message + "\n"); } f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } ``` 5. 创建客户端消息处理器 创建一个消息处理器来处理从服务器接收的消息: ``` public class ChatClientHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception { System.out.println(message); } } ``` 6. 运行Demo 在主方法中创建服务器和客户端实例并运行它们: ``` public class ChatDemo { private static final int PORT = 8080; private static final String HOST = "localhost"; public static void main(String[] args) throws Exception { ChatServer server = new ChatServer(PORT); ChatClient client = new ChatClient(HOST, PORT); new Thread(() -> { try { server.start(); } catch (Exception e) { e.printStackTrace(); } }).start(); client.start(); } } ``` 现在您已经有了一个简单Netty即时通信Demo,可以在本地计算机上启动服务器和客户端,并通过控制台输入消息进行通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值