1.序列化
public class SerializeUtils<T extends Serializable> {

    public byte[] serialize(T t) {
byte[] bytes = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(t);
bytes = byteArrayOutputStream.toByteArray();
} catch (IOException e) {
System.out.println("Serialize error");
} finally {
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
System.out.println("Close ObjectOutputStream error");
}
}
try {
byteArrayOutputStream.close();
} catch (IOException e) {
System.out.println("Close ObjectOutputStream error");
}
}
return bytes;
} public Object unserialize(byte[] bytes) {
Object object = null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
byteArrayInputStream = new ByteArrayInputStream(bytes);
objectInputStream = new ObjectInputStream(byteArrayInputStream);
object = objectInputStream.readObject();
} catch (Exception e) {
System.out.println("UnSerialize error");
} finally {
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
System.out.println("Close ObjectInputStream error");
}
}
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
System.out.println("Close ByteArrayInputStream error");
}
}
}
return object;
}
}

2.client
public class Client implements Runnable {

    private Selector selector;
SerializeUtils serializeUtils = new SerializeUtils(); public Client() throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
selector = Selector.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 9128));
socketChannel.register(selector, SelectionKey.OP_CONNECT);
} private boolean connect(SelectionKey selectionKey) throws IOException {
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
socketChannel.configureBlocking(false); if(socketChannel.isConnectionPending()){
socketChannel.finishConnect();
} UserInfo userInfo = new UserInfo();
userInfo.setPassword("12222");
userInfo.setUserName("Joe");
userInfo.setUserId(1L); byte[] arr = serializeUtils.serialize(userInfo); // TLVMessage tlvMessage = new TLVMessage();
// tlvMessage.setType(1);
// tlvMessage.setLength(arr.length);
// tlvMessage.setValue(arr); // byte[] result = serializeUtils.serialize(tlvMessage); byte[] typeArray = ByteBuffer.allocate(4).putInt(1).array();
byte[] lenArray = ByteBuffer.allocate(4).putInt(arr.length).array(); ByteBuffer byteBuffer = ByteBuffer.allocate(arr.length + 8);
byteBuffer.put(typeArray);
byteBuffer.put(lenArray);
byteBuffer.put(arr); byteBuffer.flip();
socketChannel.write(byteBuffer); System.out.println("write hello");
return true;
} @Override
public void run() { while (true){
try {
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next(); if(selectionKey.isConnectable()){
while(!connect(selectionKey)){
System.out.println("reconnect");
}
}
iterator.remove();
} } catch (IOException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) throws IOException {
new Thread(new Client()).start();
}
}
3. server

public class Server implements Runnable {

    private Selector selector;

    SerializeUtils serializeUtils = new SerializeUtils();

    public Server() throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
selector = Selector.open();
serverSocketChannel.bind(new InetSocketAddress(9128));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} public void accept(SelectionKey selectionKey) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel)selectionKey.channel(); SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} public void read(SelectionKey selectionKey) throws IOException {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
socketChannel.configureBlocking(false); ByteBuffer typeBuffer = ByteBuffer.allocate(1024);
socketChannel.read(typeBuffer);
typeBuffer.flip(); byte[] head = new byte[4];
typeBuffer.get(head);
ByteBuffer wrap = ByteBuffer.wrap(head);
System.out.println(wrap.getInt()); byte[] length = new byte[4];
typeBuffer.get(length);
ByteBuffer wrapLen = ByteBuffer.wrap(length); byte[] body = new byte[wrapLen.getInt()];
typeBuffer.get(body); UserInfo userInfo = (UserInfo)serializeUtils.unserialize(body);
System.out.println(userInfo.getUserName()); System.out.println("read data from client");
} @Override
public void run() {
while(true){
try {
selector.select();
Set<SelectionKey> sets = selector.selectedKeys();
Iterator<SelectionKey> iterator = sets.iterator(); while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
iterator.remove(); if(selectionKey.isAcceptable()){
accept(selectionKey);
} if(selectionKey.isReadable()){
read(selectionKey);
} } } catch (IOException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) throws IOException {
new Thread(new Server()).start();
}
}

nio 序列化的更多相关文章

  1. [Think In Java]基础拾遗3 - 容器、I/O、NIO、序列化

    目录 第十一章 持有对象第十七章 容器深入研究第十八章 Java I/O系统 第十一章 持有对象 1. java容器概览 java容器的两种主要类型(它们之间的主要区别在于容器中每个“槽”保存的元素个 ...

  2. Java API —— IO流(数据操作流 & 内存操作流 & 打印流 & 标准输入输出流 & 随机访问流 & 合并流 & 序列化流 & Properties & NIO)

    1.操作基本数据类型的流     1) 操作基本数据类型 · DataInputStream:数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型.应用程序可以使用数据输出 ...

  3. Java I/O流输入输出,序列化,NIO,NIO.2

    Java IO流 File类: File类是java.io包下代表和平台无关的文件和目录,File不能访问文件内容本身. File类基本操作: System.out.println("判断文 ...

  4. Tinking in Java ---Java的NIO和对象序列化

    前面一篇博客的IO被称为经典IO,因为他们大多数都是从Java1.0开始就有了的:然后今天这篇博客是关于NIO的,所以的NIO其实就是JDK从1.4开始,Java提供的一系列改进的输入/输出处理的新功 ...

  5. Netty实现高性能RPC服务器优化篇之消息序列化

    在本人写的前一篇文章中,谈及有关如何利用Netty开发实现,高性能RPC服务器的一些设计思路.设计原理,以及具体的实现方案(具体参见:谈谈如何使用Netty开发实现高性能的RPC服务器).在文章的最后 ...

  6. 【分布式】Zookeeper序列化及通信协议

    一.前言 前面介绍了Zookeeper的系统模型,下面进一步学习Zookeeper的底层序列化机制,Zookeeper的客户端与服务端之间会进行一系列的网络通信来实现数据传输,Zookeeper使用J ...

  7. Netty(五)序列化protobuf在netty中的使用

    protobuf是google序列化的工具,主要是把数据序列化成二进制的数据来传输用的.它主要优点如下: 1.性能好,效率高: 2.跨语言(java自带的序列化,不能跨语言) protobuf参考文档 ...

  8. 各种Java序列化性能比较

    转载:http://www.jdon.com/concurrent/serialization.html 这里比较Java对象序列化 XML JSON  Kryo  POF等序列化性能比较. 很多人以 ...

  9. Netty学习二:Java IO与序列化

    1 Java IO 1.1 Java IO 1.1.1 IO IO,即输入(Input)输出(Output)的简写,是描述计算机软硬件对二进制数据的传输.读写等操作的统称. 按照软硬件可分为: 磁盘I ...

随机推荐

  1. Python中if __name__ == '__main__',__init__和self 的解析

    1.2.1 一个.py文件被其他.py文件引用 假设我们有一个const.py文件,内容如下: 现在,我们写一个用于计算圆面积的area.py文件,area.py文件需要用到const.py文件中的P ...

  2. Python基础(七) python自带的三个装饰器

    说到装饰器,就不得不说python自带的三个装饰器: 1.@property   将某函数,做为属性使用 @property 修饰,就是将方法,变成一个属性来使用. class A(): @prope ...

  3. nginx----------nginx日志详细分解

    1.客户端(用户)IP地址.如:上例中的 47.52.45.228 2.访问时间.如:上例中的 [03/Jan/2013:21:17:20 -0600] 3.请求方式(GET或者POST等).如:上例 ...

  4. Unity中实现人物平滑转身

    using UnityEngine; public class PlayerController : MonoBehaviour { ; ; ; void Update() { hor = Input ...

  5. CentOS 7 MariaDB-MHA

    关于MHA    MHA(Master High Availability)是一款开源的mysql高可用程序,目前在mysql高可用方面是一个相对成熟的解决方案.MHA 搭建的前提是MySQL集群中已 ...

  6. 给学习立个flag

    今天是2018年7月7号,此时的砖相比昨天格外烫手,望着手套因被磨破而露出来的半截手指头,一股股热浪溜溜的从指间划过,背后还有小山一样高的砖头,感觉对面today店里的冰镇西瓜又成了不可奢望的梦... ...

  7. 【Spark-core学习之七】 Spark广播变量、累加器

    环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 jdk1.8 scala-2.10.4(依赖jdk1.8) spark ...

  8. java微信开发之地图定位

    页面代码: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEnc ...

  9. 论文笔记:Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks

    Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks ICML 2017 Paper:https://arxiv.org/ ...

  10. Linux系统初始配置标准化

    Inux系统标准化 配置环境:4台Centos7.6版本的虚拟机,刚刚最小化安装完成,未作任何操作,分别是node1.node2.node3.node4 本文打算利用ansible工具对这四台虚拟机进 ...