5,655
社区成员
发帖
与我相关
我的任务
分享
public class ServerSocket {
// 缓冲区大小
private static final int BufferSize=1024;
// 超时时间,单位毫秒
private static final int TimeOut=3000;
// 本地监听端口
private static final int ListenPort=1978;
public static void main(String[] args) throws IOException{
// 创建选择器
Selector selector=Selector.open();
// 打开监听信道
ServerSocketChannel listenerChannel=ServerSocketChannel.open();
// 与本地端口绑定
listenerChannel.socket().bind(new InetSocketAddress(ListenPort));
// 设置为非阻塞模式
listenerChannel.configureBlocking(false);
// 将选择器绑定到监听信道,只有非阻塞信道才可以注册选择器.并在注册过程中指出该信道可以进行Accept操作
listenerChannel.register(selector, SelectionKey.OP_ACCEPT);
// 创建一个处理协议的实现类,由它来具体操作
TCPProtocol protocol=new TCPProtocolImpl(BufferSize);
// 反复循环,等待IO
while(true){
// 等待某信道就绪(或超时)
if(selector.select(TimeOut)==0){
System.out.print("独自等待.");
continue;
}
// 取得迭代器.selectedKeys()中包含了每个准备好某一I/O操作的信道的SelectionKey
Iterator<SelectionKey> keyIter=selector.selectedKeys().iterator();
while(keyIter.hasNext()){
SelectionKey key=keyIter.next();
try{
if(key.isAcceptable()){
// 有客户端连接请求时
protocol.handleAccept(key);
}
if(key.isReadable()){
// 从客户端读取数据
protocol.handleRead(key);
}
if(key.isValid() && key.isWritable()){
// 客户端可写时
protocol.handleWrite(key);
}
}
catch(IOException ex){
// 出现IO异常(如客户端断开连接)时移除处理过的键
keyIter.remove();
continue;
}
// 移除处理过的键
keyIter.remove();
}
}
}
}
public class TCPProtocolImpl implements TCPProtocol {
private int bufferSize;
public TCPProtocolImpl(int bufferSize){
this.bufferSize=bufferSize;
}
public void handleAccept(SelectionKey key) throws IOException {
SocketChannel clientChannel=((ServerSocketChannel)key.channel()).accept();
clientChannel.configureBlocking(false);
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();
// 读取信息获得读取的字节数
long bytesRead=clientChannel.read(buffer);
if(bytesRead==-1){
// 没有读取到内容的情况
clientChannel.close();
}
else{
// 将缓冲区准备为数据传出状态
buffer.flip();
// 将字节转化为为UTF-16的字符串
String receivedString=Charset.forName("UTF-16").newDecoder().decode(buffer).toString();
// 控制台打印出来
System.out.println("接收到来自"+clientChannel.socket().getRemoteSocketAddress()+"的信息:"+receivedString);
// 准备发送的文本
String sendString="你好,客户端. @"+new Date().toString()+",已经收到你的信息"+receivedString;
buffer=ByteBuffer.wrap(sendString.getBytes("UTF-16"));
clientChannel.write(buffer);
// 设置为下一次读取或是写入做准备
key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
}
public void handleWrite(SelectionKey key) throws IOException {
// do nothing
}
}