nio 序列化
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 序列化的更多相关文章
- [Think In Java]基础拾遗3 - 容器、I/O、NIO、序列化
目录 第十一章 持有对象第十七章 容器深入研究第十八章 Java I/O系统 第十一章 持有对象 1. java容器概览 java容器的两种主要类型(它们之间的主要区别在于容器中每个“槽”保存的元素个 ...
- Java API —— IO流(数据操作流 & 内存操作流 & 打印流 & 标准输入输出流 & 随机访问流 & 合并流 & 序列化流 & Properties & NIO)
1.操作基本数据类型的流 1) 操作基本数据类型 · DataInputStream:数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型.应用程序可以使用数据输出 ...
- Java I/O流输入输出,序列化,NIO,NIO.2
Java IO流 File类: File类是java.io包下代表和平台无关的文件和目录,File不能访问文件内容本身. File类基本操作: System.out.println("判断文 ...
- Tinking in Java ---Java的NIO和对象序列化
前面一篇博客的IO被称为经典IO,因为他们大多数都是从Java1.0开始就有了的:然后今天这篇博客是关于NIO的,所以的NIO其实就是JDK从1.4开始,Java提供的一系列改进的输入/输出处理的新功 ...
- Netty实现高性能RPC服务器优化篇之消息序列化
在本人写的前一篇文章中,谈及有关如何利用Netty开发实现,高性能RPC服务器的一些设计思路.设计原理,以及具体的实现方案(具体参见:谈谈如何使用Netty开发实现高性能的RPC服务器).在文章的最后 ...
- 【分布式】Zookeeper序列化及通信协议
一.前言 前面介绍了Zookeeper的系统模型,下面进一步学习Zookeeper的底层序列化机制,Zookeeper的客户端与服务端之间会进行一系列的网络通信来实现数据传输,Zookeeper使用J ...
- Netty(五)序列化protobuf在netty中的使用
protobuf是google序列化的工具,主要是把数据序列化成二进制的数据来传输用的.它主要优点如下: 1.性能好,效率高: 2.跨语言(java自带的序列化,不能跨语言) protobuf参考文档 ...
- 各种Java序列化性能比较
转载:http://www.jdon.com/concurrent/serialization.html 这里比较Java对象序列化 XML JSON Kryo POF等序列化性能比较. 很多人以 ...
- Netty学习二:Java IO与序列化
1 Java IO 1.1 Java IO 1.1.1 IO IO,即输入(Input)输出(Output)的简写,是描述计算机软硬件对二进制数据的传输.读写等操作的统称. 按照软硬件可分为: 磁盘I ...
随机推荐
- mysql 字段唯一性问题
ALTER TABLE tb ADD unique (name);
- 抓取html 生成图片
<!DOCTYPE html> <html> <head> <script type="text/javascript" ...
- day04 一个简单的代码优化案例
import random punches = ['石头','剪刀','布'] computer_choice = random.choice(punches) user_choice = input ...
- acm 2015北京网络赛 F Couple Trees 主席树+树链剖分
提交 题意:给了两棵树,他们的跟都是1,然后询问,u,v 表 示在第一棵树上在u点往根节点走 , 第二棵树在v点往根节点走,然后求他们能到达的最早的那个共同的点 解: 我们将第一棵树进行书链剖,然后第 ...
- JavaScript 原型链学习(三)原型对象存在的问题 与 组合使用构造函数和原型
原型对象也不是没有缺点.首先,它省略了为构造函数传递初始化参数这一环节, 结果所有实例在默认情况下都将取得相同的属性值.虽然这会在某种程度上带来一些不方便, 但还不是原型对象的最大问题.原型对象的最大 ...
- c#阿里云服务器发送邮件
public static void SendMailUse() { string host = "smtp.lotusest.com";// 邮件服务器smtp.163.com表 ...
- Java面试题整理---JVM篇
1.JVM运行时内存区域划分? 2.内存溢出OOM和堆栈溢出SOE的案例.原因.排查及解决? 3.常用的JVM性能监控工具? 4.JVM参数设置? 5.类加载过程? 6.JVM内存 ...
- tomcat+apache的集群配置
背景:项目比较大,用户较多,同一时间,用户在线人数较多,为此,整体架构是lvs(2台)+keepalived(2台)+apache(N台)+tomcat(N台) lvs负责分发请求,所有的web请求经 ...
- 158A Next Round
A. Next Round time limit per test 3 seconds memory limit per test 256 megabytes input standard input ...
- python的变量和简单的数据类型
决定学习python这门语言了,本人资质愚钝,只会把学到的东西记录下来,供自己查漏补缺,也可以分享给和我一样正在学习python语言的人,若在记录中存在什么错误,希望多多批评指正,谢谢. Python ...