---
title: "ServerSocketChannel "
author: "AAries"
date: "2011-08-03T18:52:44Z"
tags: []
categories: ["编程语言"]
slug: "serversocketchannel"
draft: false
lastmod: "2011-08-03T18:54:32Z"
id: 1139433
url: "https://ati000.iteye.com/blog/1139433"
---

```java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mailclass;

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.Date;
import java.util.Iterator;
import java.util.Set;

/**
 *
 * @author AAries zyz!
 */
public class MainClass {


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        ServerSocketChannel server = ServerSocketChannel.open();
        server.configureBlocking(false);

        server.socket().bind(new InetSocketAddress(5200));

        Selector select = Selector.open();
        server.register(select, SelectionKey.OP_ACCEPT);

        while (true) {
            if (select.select(10000) == 0) {
                System.out.print("独自等待.");
                continue;
            }

            select.select();
            Set readkeys = select.selectedKeys();
            Iterator iterator = readkeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = (SelectionKey) iterator.next();
                if (key.isAcceptable()) {
                    SocketChannel client = ((ServerSocketChannel) key.channel()).accept();
                    System.out.println("Accept connection from: " + client);
                    client.configureBlocking(false);
                    client.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isWritable()) {
                    System.out.print("Write data...");
                }
                if (key.isReadable()) {

                    // 获得与客户端通信的信道
                    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);
                    }
                }
                if (key.isWritable())
                {
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer writeBuffer=ByteBuffer.wrap("我的程序员之道".getBytes("UTF-16"));
                    sc.write(writeBuffer);
                }
                key.channel().close();
            }
        }
    }
}


```


输出结果：
server端 
run：
Accept connection from: java.nio.channels.SocketChannel
接收到来自/172.16.22.11:4546的信息:我的程序员之道
独自等待.独自等待.独自等待.独自等待.独自等待.独自等待.独自等待.独自等待.独自等待.独自等待.生成已停止（总时间：1 分钟 49 秒） 
client端：
接收到来自服务器/172.16.22.11:5200的信息:你好,客户端. @Wed Aug 03 18:55:42 CST 2011，已经收到你的信息我的程序员之道
接收到来自服务器/172.16.22.11:5200的信息:
接收到来自服务器/172.16.22.11:5200的信息:
接收到来自服务器/172.16.22.11:5200的信息: