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

基于Java NIO 的socket通信实例

2016-01-22 22:12 459 查看
服务端代码

package com.lp.socket;

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.util.Iterator;

public class NioServerSocket {

public static void main(String[] args) {

HandlerSelectionKey handler = new HandlerHandlerSelectionKeyImpl();

try {
//创建 ServerSocketChannel
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
server.bind(new InetSocketAddress("localhost", 12345));
//创建 Selector
Selector selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
//死循环,持续接收 客户端连接
while(true) {
//selector.select(); 是阻塞方法
int keys = selector.select();
if(keys > 0) {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()) {
SelectionKey key = it.next();
it.remove();
//处理 SelectionKey
handler.handler(key, selector);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* SelectionKey 处理接口
*
*/
public static interface HandlerSelectionKey {

public void handler(SelectionKey key, Selector selector) throws IOException;

}

/**
* SelectionKey 接口 实现类
*
*/
public static class HandlerHandlerSelectionKeyImpl implements HandlerSelectionKey {

@Override
public void handler(SelectionKey key, Selector selector) throws IOException {
int keyState = selectionKeyState(key);
switch (keyState) {
case SelectionKey.OP_ACCEPT:
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
accept(serverSocketChannel, selector);
break;
case SelectionKey.OP_READ:
SocketChannel readSocketChannel = (SocketChannel) key.channel();
read(readSocketChannel, selector);
break;

case SelectionKey.OP_WRITE:
SocketChannel writeSocketChannel = (SocketChannel) key.channel();
write(writeSocketChannel, selector);
break;
}
}
/**
* 获取 SelectionKey 是什么事件
* @param key
* @return
*/
private int selectionKeyState(SelectionKey key) {
if(key.isAcceptable()) {
return SelectionKey.OP_ACCEPT;
} else if(key.isReadable()) {
return SelectionKey.OP_READ;
} else if(key.isWritable()) {
return SelectionKey.OP_WRITE;
}
return -1;
}

/**
* 接口客户端请求
* @param serverSocketChannel
* @param selector
* @throws IOException
*/
private void accept(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
//将 channel 注册到  Selector
socketChannel.register(selector, SelectionKey.OP_READ);
}

/**
* 读取客户端发送过来的信息
* @param socketChannel
* @param selector
* @throws IOException
*/
private void read(SocketChannel socketChannel, Selector selector) throws IOException {
ByteBuffer readBuffer = ByteBuffer.allocate(8192);
int readBytes = socketChannel.read(readBuffer);
if(readBytes > 0) {
System.out.println("客户端发送来的消息");
System.out.println(new String(readBuffer.array(), 0, readBytes));
}
//将 channel 注册到  Selector
socketChannel.register(selector, SelectionKey.OP_WRITE);
}

/**
* 响应客户端请求
* @param socketChannel
* @param selector
* @throws IOException
*/
private void write(SocketChannel socketChannel, Selector selector) throws IOException {
//响应消息
String responseMsg = "hello client, i am server";
byte[] responseByte = responseMsg.getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(responseByte.length);
writeBuffer.put(responseByte);
writeBuffer.flip();
//响应客户端
socketChannel.write(writeBuffer);
socketChannel.finishConnect();
socketChannel.close();
}

}

}


客户端代码

package com.lp.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioClientSocket {

public static void main(String[] args) throws IOException {
//打开 SocketChannel
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 12345));
//设置为 非阻塞
socketChannel.configureBlocking(false);
//给服务端发送信息
socketChannel.write(ByteBuffer.wrap("Actions speak louder than words!".getBytes()));

ByteBuffer readBuffer = ByteBuffer.allocate(512);
while (true) {
readBuffer.clear();
int readBytes = socketChannel.read(readBuffer);
if (readBytes > 0) {
readBuffer.flip();
System.out.println("Client: readBytes = " + readBytes);
System.out.println("Client: data = " + new String(readBuffer.array(), 0, readBytes));
socketChannel.close();
break;
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: