本文參考至:http://ifeve.com/socket-channel/
在NIO系列4中,采用了SocketChannel作為案例講解Selector,當時我確實看不太懂。現(xiàn)在寫一下SocketChannel的理解:
Java NIO中的SocketChannel是一個連接到TCP網(wǎng)絡(luò)套接字的通道。可以通過以下2種方式創(chuàng)建SocketChannel:
1、打開一個SocketChannel并連接到互聯(lián)網(wǎng)上的某臺服務(wù)器。
2、一個新連接到達ServerSocketChannel時,會創(chuàng)建一個SocketChannel。
這里簡要的介紹一下Channel的讀寫數(shù)據(jù)的方法,其實對于所有的Channel讀寫數(shù)據(jù)的方法都幾乎一樣,都是從Buffer中讀或者寫到Buffer中,下面舉FileChannel和SocketChannel兩個例子:
Reading from a FileChannel:
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);
Reading from a SocketChannel:
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = socketChannel.read(buf);
Writing to a SocketChannel:
String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
socketchannel.write(buf);
}
Writing Data to a FileChannel:
String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
fileChannel.write(buf);
}
以下代碼模擬了服務(wù)器和客戶端:
服務(wù)器:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
public class TCPServer {
private static final int bufferSize = 1024;
private static final long timeOut = 3000;// 超時時間
private static final int listenPort = 1993;// 本地監(jiān)聽端口
public static void main(String[] args) throws Exception {
Selector selector = Selector.open();
ServerSocketChannel listenerChannel = ServerSocketChannel.open();// 創(chuàng)建監(jiān)聽通道,專門用來監(jiān)聽指定的本地端口
listenerChannel.socket().bind(new InetSocketAddress(listenPort));// 將listenerChannel的socket綁定為本地服務(wù)器(IP+prot)綁定
listenerChannel.configureBlocking(false);
// 將選擇器綁定到監(jiān)聽信道,只有非阻塞信道才可以注冊選擇器.并在注冊過程中指出該信道可以進行Accept操作
listenerChannel.register(selector, SelectionKey.OP_ACCEPT);
TCPProtocolImpl protocol = new TCPProtocolImpl(bufferSize);
while (true) {
if (selector.select(timeOut) == 0) {// 監(jiān)聽注冊的通道,當其中有注冊的IO時該函數(shù)返回(3000ms沒有反應(yīng)返回0),操作可以進行,并添加對應(yīng)的SelectorKey
System.out.println("It haven't I/O now, please wait!");
continue;
}
Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
while (keyIter.hasNext()) {
try {
SelectionKey key = keyIter.next();
if (key.isAcceptable()) {
protocol.handleAccept(key);
}
if (key.isReadable()) {
protocol.handleRead(key);
}
} catch (IOException e) {
keyIter.remove();
continue;
}
keyIter.remove();
}
}
}
}
class TCPProtocolImpl{
private int bufferSize;
public TCPProtocolImpl() {
super();
}
public TCPProtocolImpl(int bufferSize) {
super();
this.bufferSize = bufferSize;
}
public void handleAccept(SelectionKey key) throws IOException {
// 返回創(chuàng)建此鍵的通道,接受客戶端建立連接的請求,并返回SocketChannel對象
SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept();
clientChannel.configureBlocking(false);
// 將clientChannel注冊到服務(wù)端的selector中
clientChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
}
public void handleRead(SelectionKey key) throws IOException {
// 獲取客戶端通信的通道
SocketChannel clientChannel = (SocketChannel) key.channel();
ByteBuffer buffer = (ByteBuffer) key.attachment();
buffer.clear();
// 從客戶端通道讀取信息到buffer緩沖區(qū)中(并返回讀到信息的字節(jié)數(shù))
long bytesRead = clientChannel.read(buffer);
if (bytesRead == -1) {
clientChannel.close();
} else {
buffer.flip();
// 將字節(jié)轉(zhuǎn)化為為UTF-8的字符串
String receivedString = Charset.forName("UTF-8").newDecoder().decode(buffer).toString();
System.out.println("接收到來自:" + clientChannel.socket().getRemoteSocketAddress() + "發(fā)來的信息:" + receivedString);
String msgSendToClient = "已接收到你的信息:" + receivedString + "正在處理中";
buffer = ByteBuffer.wrap(msgSendToClient.getBytes("UTF-8"));
clientChannel.write(buffer);
// 設(shè)置為下一次讀取或是寫入做準備
key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
}
}
客戶端:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;
public class TCPClient {
// 通道選擇器,用于管理客戶端的通道
private Selector selector;
// 與服務(wù)器通信的通道
SocketChannel socketChannel;
// 要連接的服務(wù)器的IP
private String hostIp;
// 要連接的遠程服務(wù)器在監(jiān)聽的端口
private int hostListenningPort;
static TCPClient client;
static boolean mFlag = true;
public TCPClient(String hostIp, int hostPort) throws IOException {
this.hostIp = hostIp;
this.hostListenningPort = hostPort;
init();
}
private void init() throws IOException {
// 打開監(jiān)聽通道
socketChannel = SocketChannel.open(new InetSocketAddress(hostIp, hostListenningPort));
socketChannel.configureBlocking(false);
// 創(chuàng)建選擇器,并把通道注冊到選擇器中
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_READ);
new TCPClientReadThread(selector);
}
/**
* 發(fā)送字符串到服務(wù)器
* @param message
* @throws IOException
*/
public void sendMsg(String message) throws IOException{
ByteBuffer writeBuffer = ByteBuffer.wrap(message.getBytes("UTF-8"));
socketChannel.write(writeBuffer);
}
public static void main(String[] args) throws IOException {
client = new TCPClient("127.0.0.1", 1993);
new Thread(){
@Override
public void run(){
try{
client.sendMsg("test----~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
while(mFlag){
Scanner scan = new Scanner(System.in);
String string = scan.next();
client.sendMsg(string);
}
}catch (Exception e) {
mFlag = false;
}finally{
mFlag = false;
}
super.run();
}
}.start();
}
}
class TCPClientReadThread implements Runnable {
private Selector selector;
public TCPClientReadThread(Selector selector) {
super();
this.selector = selector;
new Thread(this).start();
}
@Override
public void run() {
try {
while (selector.select() > 0) {// select()方法只能使用一次,用了之后就會自動刪除,每個連接到服務(wù)器的選擇器都是獨立的
// 遍歷每個有IO操作Channel對應(yīng)的SelectionKey
for (SelectionKey sk : selector.selectedKeys()) {
if (sk.isReadable()) {
// 使用NIO讀取Channel中的數(shù)據(jù)
SocketChannel sc = (SocketChannel) sk.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
sc.read(buffer);
buffer.flip();
String receivedString = Charset.forName("UTF-8").newDecoder().decode(buffer).toString();
System.out.println("接收到來自服務(wù)器:" + sc.socket().getRemoteSocketAddress() + "的信息:" + receivedString);
sk.interestOps(SelectionKey.OP_READ);
}
selector.selectedKeys().remove(sk);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}