文章目录

1、步骤2、Server3、Client

Discard服务器仅读取客户端输入的数据,立马关闭信道后丢弃数据

1、步骤

生成服务器信道信道绑定ip、port设置为非阻塞并注册到选择器为接收模式select轮询已注册的就绪事件对就绪事件进行相应处理接收就绪,获取连接信道并设置非注册注册到选择器为读模式读就绪,获取连接信道读后直接丢弃数据

注意:注册到选择器上的信道必须为非阻塞模式,文件信道不支持非阻塞就必定不能注册选择器

2、Server

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.*;

import java.util.Iterator;

public class DiscardServer implements Runnable{

public static void main(String[] args) {

new Thread(new DiscardServer(8090)).start();

}

private int port;

DiscardServer(int port){

this.port = port;

}

@Override

public void run() {

ServerSocketChannel server = null;

Selector selector = null;

try {

server = ServerSocketChannel.open();

server.bind(new InetSocketAddress(port));

server.configureBlocking(false);//非阻塞

selector = Selector.open();

server.register(selector, SelectionKey.OP_ACCEPT);//注册到选择器

while(selector.select() > 0){

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

while(selectionKeys.hasNext()){

SelectionKey selectionKey = selectionKeys.next();

if(selectionKey.isAcceptable()){

//接受到连接就设置非阻塞注册到选择器

System.out.println("收到连接");

SocketChannel client = server.accept();

client.configureBlocking(false);//非阻塞

client.register(selector, SelectionKey.OP_READ);

}else if(selectionKey.isReadable()){

//读任务就丢弃

System.out.println("收到读");

SocketChannel clientChannel =(SocketChannel) selectionKey.channel();

ByteBuffer buffer = ByteBuffer.allocate(1024);

int len = -1;

while( (len = clientChannel.read(buffer)) != -1){

buffer.flip();

System.out.println(new String(buffer.array(), 0, len));

buffer.clear();

}

clientChannel.close();

}

selectionKeys.remove();

}

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if(selector != null){

try {

selector.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(server != null){

try {

server.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

3、Client

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SocketChannel;

import java.util.Scanner;

public class C1Demo {

public static void main(String[] args) {

SocketChannel socketChannel = null;

try {

socketChannel = SocketChannel.open();

socketChannel.configureBlocking(false);

socketChannel.connect(new InetSocketAddress("127.0.0.1",8090));

while(!socketChannel.finishConnect()){

}

System.out.println("获取到连接");

ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

Scanner sc = new Scanner(System.in);

String msg = sc.nextLine();

byteBuffer.put(msg.getBytes());

byteBuffer.flip();

socketChannel.write(byteBuffer);

byteBuffer.clear();

socketChannel.shutdownOutput();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if(socketChannel != null)

socketChannel.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

文章来源

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: