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();
}
}


原文地址:https://www.cnblogs.com/sidesky/p/10617454.html