最近学习服务器,研究下Socket,初步流程代码(待整理)
package NIOTest;
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.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by Yu on 2017/1/20.
* Desc:
*/
public class EscoServer {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
Selector selector=Selector.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
HashMap<Integer,SocketChannel> session=new HashMap<>();
int useSessionId=1;
ByteBuffer buffer=ByteBuffer.allocate(1000);
while (true)
{
if(selector.select()<0)
continue;
Set<SelectionKey> selected=selector.selectedKeys();
for(SelectionKey selectionKey :selected)
{
if (selectionKey.isAcceptable())
{
ServerSocketChannel server=(ServerSocketChannel)selectionKey.channel();
SocketChannel clientChannel=server.accept();
Integer sessionId=useSessionId++;
session.put(sessionId,clientChannel);
clientChannel.configureBlocking(false);
clientChannel.register(selector,SelectionKey.OP_READ,sessionId);
buffer.clear();
buffer.put(ByteBuffer.wrap("Success\n".getBytes()));
buffer.flip();
clientChannel.write(buffer);
}
else if(selectionKey.isReadable())
{
SocketChannel client=(SocketChannel)selectionKey.channel();
Integer sessionId=(Integer) selectionKey.attachment();
buffer.clear();
long byteRead=client.read(buffer);
System.out.print("Over");
System.out.print(byteRead);
System.out.print("\n");
buffer.flip();
if(-1==byteRead)
{
System.out.print(client.getRemoteAddress().toString()+"......Close");
session.remove(sessionId);
client.close();
}
else if(byteRead>2) {
System.out.print(byteRead);
String receivedString=Charset.forName("UTF-8").newDecoder().decode(buffer).toString();
System.out.print("Read:");
System.out.print(receivedString);
System.out.print("\n");
if(session.size()>1)
{
for (SocketChannel channel :session.values())
{
if(client !=channel) {
buffer.clear();
buffer.put(ByteBuffer.wrap(receivedString.getBytes()));
buffer.flip();
channel.write(buffer);
}
}
}
}
}
}
selected.clear();
}
}
}