java实现netty对象传输超简单例子

半兽人 发表于: 2018-01-09   最后更新时间: 2021-09-06 20:27:21  
{{totalSubscript}} 订阅, 9,189 游览

这是一个简单的java服务器/客户端,实现对象传输,可以直接运行。

项目结构

 src
 ├── main
 │   ├── java
 │   │   └── com
 │   │       └── system
 │   │           └── net
 │   │               └── netty
 │   │                   ├── client
 │   │                   │   ├── Client.java
 │   │                   │   └── ClientHandler.java
 │   │                   ├── model
 │   │                   │   └── Command.java
 │   │                   └── server
 │   │                       ├── Server.java
 │   │                       └── ServerHandler.java
 │   └── resources
 └── test
     └── java

服务端

package com.system.net.netty.server;


import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

public class Server {
    public static void main(String[] args) throws Exception {
        ChannelFactory factory = new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());
        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("encode", new ObjectEncoder());
                pipeline.addLast("decode", new ObjectDecoder());
                pipeline.addLast("handler", new ServerHandler());
                return pipeline;
            }
        });
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);
        bootstrap.bind(new InetSocketAddress(8080));
    }
}

服务端处理消息类

package com.system.net.netty.server;

import com.system.net.netty.model.Command;
import org.jboss.netty.channel.*;

public class ServerHandler extends SimpleChannelHandler {

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelConnected");
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelDisconnected");
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        if (e.getMessage() instanceof Command) {
            Command command = (Command) e.getMessage();
            System.out.println("对象:" + command.getActionName());
        }

        // 向客户端发送收到结果
        Command command = new Command();
        command.setActionName("Hello Client.");
        e.getChannel().write(command);
    }

    @Override
    public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        System.out.println("writeRequested");
        super.writeRequested(ctx, e);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        System.out.println("exceptionCaught");
        e.getCause().printStackTrace();
        Channel ch = e.getChannel();
        ch.close();
    }
}

客户端

package com.system.net.netty.client;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

public class Client {
    public static void main(String[] args) throws Exception {

        ChannelFactory factory = new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());
        ClientBootstrap bootstrap = new ClientBootstrap(factory);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("encode", new ObjectEncoder());
                pipeline.addLast("decode", new ObjectDecoder());
                pipeline.addLast("handler", new ClientHandler());
                return pipeline;
            }
        });
        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setOption("keepAlive", true);
        bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));
    }
}

客户端处理类

package com.system.net.netty.client;

import com.system.net.netty.model.Command;
import org.jboss.netty.channel.*;

public class ClientHandler extends SimpleChannelUpstreamHandler {

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
        Command command = new Command();
        command.setActionName("Hello Server.");
        e.getChannel().write(command);
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        if (e.getMessage() instanceof Command) {
            Command command = (Command) e.getMessage();
            System.out.println("对象:" + command.getActionName());
            return;
        }

        System.out.println(e.getMessage());
        e.getChannel().close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();
        e.getChannel().close();
    }
}

传输对象

package com.system.net.netty.model;

import java.io.Serializable;

public class Command implements Serializable {

    private static final long serialVersionUID = 1320123451767766661L;

    private String actionName;

    public String getActionName() {
        return actionName;
    }

    public void setActionName(String actionName) {
        this.actionName = actionName;
    }
}

我把这些代码放到了github上了:https://github.com/orchome/net

更新于 2021-09-06

查看java更多相关的文章或提一个关于java的问题,也可以与我们一起分享文章