nio java 例子_java的nio例子

package main;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

//import java.nio.channels.ClosedChannelException;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.util.Iterator;

public class JsonSocketServer{

private static int PORT = 9090;

public static void main(String[] args) {

System.out.println("Server try start ..");

Selector selector = null;

ServerSocketChannel serverSocketChannel = null;

try{

selector = Selector.open();

serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.configureBlocking(false);

serverSocketChannel.socket().setReuseAddress(true);

serverSocketChannel.socket().bind(new InetSocketAddress(PORT) );

//注册可读事件

serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

while (selector.select()>0) {//select()可指定超时参数

Iterator it = selector.selectedKeys().iterator();

while (it.hasNext()) {

SelectionKey readyKey = it.next();

it.remove();

handleConnection((ServerSocketChannel) readyKey.channel());

}

}

}catch (IOException e){

System.out.println("IO:"+e.getMessage());

}catch (Exception e){

e.printStackTrace();

}finally{

try{

serverSocketChannel.close();

selector.close();

}catch (Exception e) {

e.printStackTrace();

}

}

}

private static void handleConnection(ServerSocketChannel serverSocketChannel) throws IOException {

SocketChannel socketChannel = null;

try{

socketChannel = serverSocketChannel.accept();

socketChannel.configureBlocking(false);

String recvShow = new String(recevceData(socketChannel));

//System.out.println("recv :"+recvShow);

sendData(socketChannel);

} catch (IOException e) {

System.out.println("IO"+e.getMessage());

} catch (Exception e) {

e.printStackTrace();

}finally{

socketChannel.close();

}

}

private static byte[] recevceData(SocketChannel socketChannel) throws IOException {

int datagramHead = 4;

int recvTimes = 5;

//方法使用的数据类型 ByteBuffer java.nio.channels.SocketChannel.read(ByteBuffer arg0) throws IOException

ByteBuffer buffer = ByteBuffer.allocate(1500);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] bytes=null;

int len,lenInfo=-1,offset=0;

String s;

try {

while(true){

len = socketChannel.read(buffer);

if(len<0){

System.out.println("read return "+len);

break;

}

offset += len;

if(len == 0){

if(lenInfo + datagramHead <= offset && lenInfo != -1){

break;

}

else {

if(--recvTimes == 0)

break;

Thread.sleep(10);

continue;

}

}

buffer.flip();//复位ByteBuffer.position

bytes = new byte[len];

buffer.get(bytes);//把position到limit之间的数据复制到bytes,position会变化

baos.write(bytes);//将本次接收写入缓冲区

if(lenInfo == -1){

s = new String(baos.toByteArray());

lenInfo = Integer.parseInt(s.substring(0,datagramHead));

//System.out.println("len is "+lenInfo);

if(lenInfo + datagramHead <= offset){

break;

}

}

buffer.clear();//恢复buffer的初始状态

}

if(len >= 0){

bytes = baos.toByteArray();

}

else {

bytes = new byte[0];

}

}catch (IOException e) {

System.out.println("IO"+e.getMessage());

} catch (Exception e) {

e.printStackTrace();

}finally{

baos.close();//关闭缓冲区

}

return bytes;

}

private static void sendData(SocketChannel socketChannel)throws IOException {

String responseString = "heeeeeee";

//将bytes数组内容写入buffer

ByteBuffer buffer = ByteBuffer.wrap(responseString.getBytes());

try{

socketChannel.write(buffer);

}catch (IOException e) {

System.out.println("IO:"+e.getMessage());

}

catch (Exception e) {

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值