您的位置:首页 > 编程语言 > Java开发

Java NIO 学习(四)--ServerSocketChannel与SocketChannel

2016-07-13 17:53 597 查看
本机要讲到的ServerSocketChannel、SocketChannel,与Java网络编程中的ServerSocket、Socket是非常相识,至少从使用方式上来看是这样,本质上都是TCP网络套接字,只是多了“channel”;

一、SocketChanel

1、创建SocketChannel

有两种方法可以获取一个SocketChannel实例

1. 通过静态方法open打开一个

SocketChannel socketChannel = SocketChannel.open();


ServerSocketChannel接受一个连接请求后等到

SocketChannel socketChannel = serverSocketChannel.accept();


获取到实例后可通过connect方法与服务端建立连接:

socketChannel.connect(new InetSocketAddress(1234));


2、读写数据

SocketChannel的读写数据与其他通道没有区别,读数据使用多个read方法,将数据读取如一个buffer中,返回一个int值,表示成功读取的字节数,返回-1表示读取到了数据流的末尾了;

sizeBuffer.clear();
int read = socketChannel.read(sizeBuffer);


使用write方法将buffer中的数据写入到通道中,同样需要循环写入;

buffer.flip();
while (buffer.hasRemaining()) {
socketChannel.write(dest);
}


3、非阻塞模式

非阻塞就是普通套接字的区别了,SocketChannel在非阻塞模式下,许多方法都是可能直接返回不等待的:

1. connect方法,可能没有完成连接建立就已经返回,需要使用finishConnect,判断是否完成了连接;

2. read方法,可能没有读取任何就返回了(不是到数据末尾),需要通过返回值判断;

3. write方法,与阻塞模式一样,需要在循环中写入;

二、ServerSocketChannel

1、创建ServerSocketC

通过静态方法open获取一个实例,并使用bind方法绑定地址:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(1234));


完成绑定后,可以通过accept方法,接受客户端连接请求,与客户端建立连接后,获取到一个SocketChannel实例,通过这个实例与建立连接的客户端进行通信;

2、非阻塞模式

ServerSocketChannel同样有非阻塞模式,此时,accept方法在没有连接请求是,可能返回Null,需要做判断处理;

三、结合实例

通过ServerSocketChannel 和 SocketChannel实现一个简单的消息发送例子:

1、服务端

服务端在循环中等待客户端连接请求(阻塞模式下),对每一个请求使用一个单独的线程进行通信处理

public class ServerSocketChannelServer {

public static void main(String[] args) throws IOException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 10, 1000, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(100));

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress(1234));

while (true) {
SocketChannel socketChannel = serverSocketChannel.accept();
//每个连接使用一个单独线程处理
if (socketChannel != null) {
executor.submit(new SocketChannelThread(socketChannel));
}
}
}
}


2、处理线程

public class SocketChannelThread implements Runnable {

private SocketChannel socketChannel;
private String remoteName;

public SocketChannelThread(SocketChannel socketChannel) throws IOException {
this.socketChannel = socketChannel;
this.remoteName = socketChannel.getRemoteAddress().toString();
System.out.println("客户:" + remoteName + " 连接成功!");
}

@Override
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteBuffer sizeBuffer = ByteBuffer.allocate(4);
StringBuilder sb = new StringBuilder();
byte b[];
while(true) {
try {
sizeBuffer.clear(); int read = socketChannel.read(sizeBuffer);
if (read != -1) {
sb.setLength(0);
sizeBuffer.flip();
int size = sizeBuffer.getInt();
int readCount = 0;
b = new byte[1024];
//读取已知长度消息内容
while (readCount < size) {
buffer.clear();
read = socketChannel.read(buffer);
if (read != -1) {
readCount += read;
buffer.flip();
int index = 0 ;
while(buffer.hasRemaining()) {
b[index++] = buffer.get();
if (index >= b.length) {
index = 0;
sb.append(new String(b,"UTF-8"));
}
}
if (index > 0) {
sb.append(new String(b,"UTF-8"));
}
}
}
System.out.println(remoteName + ":" + sb.toString());
}
} catch (Exception e) {
System.out.println(remoteName + " 断线了,连接关闭");
try {
socketChannel.close();
} catch (IOException ex) {
}
break;
}
}
}

}


消息的发送和接收,在消息的前4个字节固定发送后面消息的内容长度,接收时,按照长度接收消息内容,使用这个方式的来解决“消息无边界”问题;

3、客户端

使用“分散(Scatter)”方式写入

public class SocketChanneClient {

public static void main(String[] args) throws IOException {

SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress(1234));
while (true) {
Scanner sc = new Scanner(System.in);
String next = sc.next();
sendMessage(socketChannel, next);
}
}

public static void sendMessage(SocketChannel socketChannel, String mes) throws IOException {
if (mes == null || mes.isEmpty()) {
return;
}
byte[] bytes = mes.getBytes("UTF-8");
int size = bytes.length;
ByteBuffer buffer = ByteBuffer.allocate(size);
ByteBuffer sizeBuffer = ByteBuffer.allocate(4);

sizeBuffer.putInt(size);
buffer.put(bytes);

buffer.flip();
sizeBuffer.flip();
ByteBuffer dest[] = {sizeBuffer,buffer};
while (sizeBuffer.hasRemaining() || buffer.hasRemaining()) {
socketChannel.write(dest);
}
}
}


总最后的例子来看,确实与平常的网络套接字没有什么区别,可以看出的最大区别应该就是非阻塞模式了;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java nio