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. git忽略规则.gitignore未生效解决办法

    创建git本地的仓库常用命令:git init #初始化--------生成.git文件 配置本地用户名跟邮箱(这样就知道是谁提交的东西)git config --global user.name [ ...

  2. 菜鸟手下的iOS开发笔记(swift)

    在阳春4月的一天晨会上,有一个老板和蔼的对他的一个菜鸟手下说:“你既然会Android,那你能不能开发iOS?” 不是说好的要外包的吗?内心跌宕,但是表面淡定的菜鸟手下弱弱的回道:“可以试试”. 第二 ...

  3. memcache 常用方法

    <?php $memcache = new Memcache; //initialised memcahe $memcache->connect("127.0.0.1" ...

  4. 【转】Sqlserver将数据从一个表插入到另一个表

    -- 复制表结构CREATE TABLE empty_table_name LIKE table_name; --根据table_name创建一个空表empty_table_name,empty_ta ...

  5. apache+jk+tomcat+ssl的https改造

    项目背景 公司项目要进行https的改造,目前在测试环境搭建了一下,参考了网上的例子(http://blog.csdn.net/whumr1/article/details/7804992) 这里把主 ...

  6. 常用模块 time sys os json pickle

    # import time # print(time.time()) #秒数 # print('开始下载') # time.sleep(2) # print('下载完成') # print(time. ...

  7. 5、Kafka生产过程分析

    1.写入方式 producer采用推(push)模式将消息发布到broker, 每条消息都被追加(append)到分区(patition)中,属于顺序写磁盘(顺序写磁盘效率比随机写内存要高,保障kaf ...

  8. gcc、make编译

    一 arm-linux-gcc 常用参数 https://www.cnblogs.com/zhangpengshou/p/3587751.html 二 arm-linux-objdump常用参数 ht ...

  9. 搭建Elasticsearch平台

    https://cloud.tencent.com/developer/article/1189282 https://blog.csdn.net/qq_34021712/article/detail ...

  10. 关于乱码(MessyCode)问题

    乱码本质:读取二进制时采用的编码和最初将字符转成二进制时的编码不一致 编码时(得二进制数组时)不抛出异常,数据就不会被破坏 Java关于乱码(MessyCode)问题 Java使用的是Unicode编 ...