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框架之Django(10)-Form组件

    介绍 我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来.与此同时我们在好多场景下都需要对用户的输入做校验,比如校验用户是否输入,输入 ...

  2. python基础之 编码进阶,文件操作和深浅copy

    1.编码的进阶 字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码.即先将其他编码的字符串解码(decode)成unicode,再从unic ...

  3. 110A

    #include <stdio.h> #include<string.h> #define MAXSIZE 30 int main() { char digits[30]; m ...

  4. linux系统644、755、777权限详解

    在linux系统中644.755.777三种权限是非常重要的一些权限了,下面我来详细的介绍644.755.777三种权限的使用,希望对各位有帮助. 常用的linux文件权限:444 r--r--r-- ...

  5. [JavaScript] Frequently used method or solutions for issues

    Get the file name from the file path Solution: var fileName = fullPath.replace(/^.*[\\\/]/, ''); // ...

  6. OAuth2认证和授权:AuthorizationCode认证

    前面的OAuth2认证,里面的授权服务器都是用的identityserver4搭建的 ids4没有之前一般都是Owin搭建授权服务器,博客园有很多 ids4出来后,一般都是用ids4来做认证和授权了, ...

  7. Django框架详细介绍---模型---ORM

    一.概述 ORM(Object Relational Mapping),全称:对象关系映射,简单的说就是通过创建类.实例化出对象的方法,使得类.对象.对象的属性能够和数据库中的表.记录.字段意义对应. ...

  8. python_study-1

    # Author:larlly'''函数1.在Python交互式命令行下,可以直接输入代码,然后执行,并立刻得到结果.2.文本编辑器推荐俩款 http://www.sublimetext.com/ h ...

  9. Maven Web Project设置Webcontent路径

    1,新建maven-archetype-webapp 2,右键项目-->Properties-->选中Project Facets中的Runtimes标签,然后Java版本改为1.8,Dy ...

  10. EDK II之Device Path

    UEFI中通过Device Path来描述设备的路径,一个完整的路径由多个Device Path Nodes组成. 下面通过输入设备的路径作为例子: PNP0A03 – PCI Host Bridge ...