⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 writerhandler.java

📁 java NIO源代码,初学者学习java NIO技术的基础代码
💻 JAVA
字号:
package org.Arios.XHandler;

import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

import org.Arios.XWrap.Request;
import org.Arios.XWrap.Response;

public class WriterHandler extends Handler implements Runnable {
	private static final int CAST = 0;
	private static final int REQUEST = 1;
	private SelectionKey key;

	public WriterHandler(SelectionKey key) {
		this.key = key;
	}

	/**
	 * 发送线程主控服务方法,负责调度整个处理过程
	 */
	@Override
	public void run() {
		// 处理写事件
		try {
			write(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 处理向客户发送数据
	 * 
	 * @param key
	 *            SelectionKey
	 * @throws Exception
	 */
	public void write(SelectionKey key) throws Exception {
		Request request = (Request) key.attachment();
		int optType = (Integer) request.attachment();
		switch (optType) {
		case REQUEST:
			try {
				SocketChannel sc = (SocketChannel) key.channel();
				Response response = new Response(sc);
				// 触发onWrite事件
				// notifier.callOnWrite(request, response);
				request.attach(2);
				key.interestOps(SelectionKey.OP_READ);
			} catch (Exception e) {
				// 触发关闭连接事件
				// notifier.callOnClosed(request);
				// notifier.callOnError("Error occured in Writer: " +
				// e.getMessage());
			}
			break;
		case CAST:
			break;
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -