Netty4 服务器 客户端 传输对象

关键词:netty4  对象  序列化

废话少说,直接上代码了

Client.java

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

import io.netty.bootstrap.Bootstrap;

import io.netty.channel.*;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioSocketChannel;

import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import io.netty.handler.codec.LengthFieldPrepender;

import io.netty.handler.codec.serialization.ClassResolvers;

import io.netty.handler.codec.serialization.ObjectDecoder;

import
io.netty.handler.codec.serialization.ObjectEncoder;

public
class Client

{

    public
Student SendAndGet(String ip,int
port,Student s)

    {

        EventLoopGroup group = new
NioEventLoopGroup();

        Student ret=null;

        try

        {

            Bootstrap b = new
Bootstrap();

            b.group(group);

            final
ClientHandler chl=new
ClientHandler();

            b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);

            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);

            b.handler(new
ChannelInitializer<SocketChannel>() {

                @Override

                protected
void initChannel(SocketChannel ch) throws
Exception {

                    ChannelPipeline pipeline = ch.pipeline();

                    pipeline.addLast("frameDecoder", new
LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

                    pipeline.addLast("frameEncoder", new
LengthFieldPrepender(4));

                    pipeline.addLast("encode", new
ObjectEncoder()); 

                    pipeline.addLast("decode", new
ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));

                    pipeline.addLast("handler", chl);

                }

            });

            ChannelFuture f = b.connect(ip, port).sync();

            f.channel().writeAndFlush(s);

            f.channel().closeFuture().sync();

            ret=chl.getMessage();

        }

        catch
(Exception e)

        {

            e.printStackTrace();

        }

        finally

        {

            group.shutdownGracefully();

        }

        return
ret;

    }

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

        

            Student s=new
Student("hello",23);

            Student g=new
Client().SendAndGet("localhost",9988,s);

           

        

    }

}

ClientHandler.java

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientHandler extends
ChannelInboundHandlerAdapter

{

    private
Student student;

    @Override

    public
void channelRead(ChannelHandlerContext ctx, Object msg) throws
Exception

    {

        System.out.println("client接收到服务器返回的消息");

        student=(Student)msg;

    }

    public
Student getMessage()

    {

        return
this.student;

    }

    @Override

    public
void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws
Exception

    {

        System.out.println("client exception is general");

    }

}

Server.java

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.ChannelOption;

import io.netty.channel.ChannelPipeline;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioServerSocketChannel;

import
io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import
io.netty.handler.codec.LengthFieldPrepender;

import
io.netty.handler.codec.serialization.ClassResolvers;

import
io.netty.handler.codec.serialization.ObjectDecoder;

import
io.netty.handler.codec.serialization.ObjectEncoder;

public
class Server {

    private
static final String IP = "localhost";

    private
static final int PORT = 9988;

    protected
static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors() * 2;

    protected
static final int BIZTHREADSIZE = 4;

    private
static final EventLoopGroup bossGroup = new
NioEventLoopGroup(BIZGROUPSIZE);

    private
static final EventLoopGroup workerGroup = new
NioEventLoopGroup(BIZTHREADSIZE);

    protected
void run() throws
Exception {

        try

        {

              ServerBootstrap b = new
ServerBootstrap();

                b.group(bossGroup, workerGroup);

                b.channel(NioServerSocketChannel.class);

                b.option(ChannelOption.SO_BACKLOG, 1000000);

                b.childHandler(new
ChannelInitializer<SocketChannel>() {

                    @Override

                    public
void initChannel(SocketChannel ch) throws
Exception {

                        ChannelPipeline pipeline = ch.pipeline();

                        pipeline.addLast(new
LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

                        pipeline.addLast(new
LengthFieldPrepender(4));

                        pipeline.addLast("encode", new
ObjectEncoder()); 

                        pipeline.addLast("decode", new
ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));

                        pipeline.addLast(new
ServerHandler());

                    }

                });

                ChannelFuture f = b.bind(IP, PORT).sync();

                f.channel().closeFuture().sync();

        }

        finally

        {

             workerGroup.shutdownGracefully();

             bossGroup.shutdownGracefully();

        }

      

    }

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

        System.out.println("开始启动服务器...");

        new
Server().run();

//        HelloServer.shutdown();

    }

}

ServerHandler.java

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends
ChannelInboundHandlerAdapter

{

    @Override

    public
void channelRead(ChannelHandlerContext ctx, Object msg) throws
Exception

    {

        Student s=(Student)msg;

        System.out.println("SERVER接收到消息");

        ctx.channel().writeAndFlush(new
Student("world",23));

        ctx.close();

    }

    @Override

    public
void channelActive(ChannelHandlerContext ctx) throws
Exception

    {

        System.out.println(">>>>>>>>");

    }

    @Override

    public
void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws
Exception

    {

        System.out.println("exception is general");

    }

}

Student.java.需要传输的对象。别忘了implements Serializable

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import java.io.Serializable;

public class Student implements
Serializable 

{

    /**

     *

     */

    private
static final long serialVersionUID = 1L;

    private
String name;

    private
int
age;

    public
Student(String name,int
age)

    {

        this.name=name;

        this.age=age;

    }

    public
String getName() {

        return
name;

    }

    public
void setName(String name) {

        this.name = name;

    }

    public
int getAge() {

        return
age;

    }

    public
void setAge(int
age) {

        this.age = age;

    }

}

  

时间: 2024-10-08 02:48:40

Netty4 服务器 客户端 传输对象的相关文章

巧用Android网络通信技术,在网络上直接传输对象

本文首发于CSDN博客,转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/8967080 要做一个优秀的Android应用,使用到网络通信技术是必不可少的,很难想象一款没有网络交互的软件最终能发展得多成功.那么我们来看一下,一般Android应用程序里都是怎么实现网络交互的,这里拿一个Boook对象为例: 如上图所示,首先在手机端生成一个Book对象,里面包含书名.作者.价格等数据.为了要将这些数据发送到服务器端,我们要从Book对

第5章分布式系统模式 使用客户端激活对象通过 .NET Remoting 实现 Broker

正在 .NET 中构建一个需要使用分布式对象的应用程序,并且分布式对象的生存期由客户端控制.您的要求包括能够按值或按引用来传递对象,无论这些对象驻留在同一台计算 机上,还是驻留在同一个局域网 (LAN) 中的不同计算机上,或者是驻留在广域网 (WAN) 中的不同计算机上. 实现策略 这 种模式为在 .NET Remoting 中实现客户端激活对象提供了两种实现方式.客户端激活对象 (CAO) 和服务器激活对象 (SAO) 之间的主要区别在于,是什么控制着远程对象的生存期.在使用 CAO 的情况下

Netty 4 传输对象

对于Netty在这里就不做过多介绍了,详情咨询http://netty.io/wiki/user-guide-for-4.x.html 我们在使用netty的过程中肯定会遇到传输对象的情况,Netty4通过ObjectEncoder和ObjectDecoder来支持. 首先我们定义一个User对象,一定要实现Serializable接口: import java.io.Serializable; /** * User: hupeng * Date: 14-6-3 * Time: 上午1:31 *

c++下基于windows socket的单线程服务器客户端程序

今天自己用编写了一个简单的c++服务器客户端程序,注释较详细,在此做个笔记. windows下socket编程的主要流程可概括如下:初始化ws2_32.dll动态库-->创建套接字-->绑定地址信息-->服务器进行监听/客户端连接服务器-->数据交换-->关闭套接字对象. 服务器端: 1 #include <Winsock2.h> 2 #include <Ws2tcpip.h> 3 #include <iostream> 4 5 #prag

Mina使用总结(四)传输对象ObjectSerializationCodecFactory

用mina框架传输对象,对于开发者来说,直接传输对象,而不用自己编写相应的报文转换代码,将大大节省 开发时间. 即使用对象编码解码器 使用ObjectSerializationCodecFactory 服务端 MinaServer.java代码如下 package com.bypay.mina.server; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress;

图文:CentOS 下对 Nginx + Tomcat 配置 SSL 实现服务器 / 客户端双向认证

1. 安装 nginx 1.1 nginx 包及其依赖包下载 出于模块的依赖性,Nginx 依赖以下三个包: gzip 模块需要 zlib 库(http://www.zlib.net/): rewrite 模块需要 pcre 库(http://www.pcre.org/): ssl 功能需要 openssl 库(http://www.openssl.org/): 分别下载它们的最新稳定版(截至本文最新稳定版分别是 zlib-1.2.8.tar.gz.pcre-8.36.tar.gz.openss

Java 利用 Socket 实现服务器客户端聊天

Socket是网络编程中最基本的通信接口,常用的网络辅助类,比如URL等之类,其底层还是基于Socket来实现的. 而Socket,形象来说,就是连接通信的两端,比如这样 S<==>S,中间的通道就是网络了,而简单地利用Socket,我们就可以来实现一个简单的聊天功能 具体效果看下图: 这只是在本地中试用的效果,如果加上UI界面,其实就可以做成一个聊天的小应用了. 1. Server 端主要是利用ServerSocket的accept方法来等待客户端的连接,如果客户一直没有连接,则会在这里等待

vsftp服务器被动传输文件配置

vsftp服务器被动传输文件配置: iptables设置 vi /etc/sysconfig/iptables 添加规则 -A INPUT -p tcp -m multiport --dport 21,10045:10090 -j ACCEPT 添加iptables内核模块 modprobe ip_nat_ftp 编辑iptables模块加载文件 vi /etc/sysconfig/iptables-config IPTABLES_MODULES="ip_nat_ftp" 重启ipta

Netty JDK序列化编解码传输对象

JDK序列化不需要额外的类库,只需要实现Serializable即可,但是序列化之后的码流只有Java才能反序列化,所以它不是跨语言的,另外由于Java序列化后码流比较大,效率也不高,所以在RPC中很少使用,本文只是做学习之用. 编解码器: public class JdkDecoder extends MessageToMessageDecoder<ByteBuf> { @Override protected void decode(ChannelHandlerContext channel