登录 之 服务端响应(一)

2014-11-24 11:36:21 · 作者: · 浏览: 27
前面讲到的关于通讯机制的实现是客户端,现在将服务端响应的部分实现予以展示
[java]
package com.net;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
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.Hashtable;
import java.util.Iterator;
import java.util.Set;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class NioServer {
private ReadProperties rp = new ReadProperties();
private final String IP = rp.getProperty("ip");
private final int SERVERPORT = Integer.parseInt(rp
.getProperty("socketport"));
private final String ISACK = "ACK";
private final String ISNAK = "NAK!";
private final String SPLITSTR = rp.getProperty("split_string");
private ConnectionPool connpool=null;
private Connection conn=null;
private PreparedStatement pstmt=null;
private ResultSet rs = null;
private Hashtable htMap=new Hashtable();
// Selector selector;//选择器
// SelectionKey key;//key。 一个key代表一个Selector 在NIO通道上的注册,类似主键;//
// 取得这个Key后就可以对Selector在通道上进行操作
private ByteBuffer echoBuffer = ByteBuffer.allocate(1024); // 通道数据缓冲区
public NioServer() {
this.initHashTable();
}
private void initHashTable(){
htMap.put("land", 1);
htMap.put("register", 2);
}
public void BuildNioServer() throws IOException {
// ///////////////////////////////////////////////////////
// ///////先对服务端的ServerSocket进行注册,注册到Selector ////
// ///////////////////////////////////////////////////////
ServerSocketChannel ssc = ServerSocketChannel.open(); // 新建NIO通道
ssc.configureBlocking(false); // 使通道为非阻塞,false
ServerSocket ss = ssc.socket(); // 创建基于NIO通道的socket连接
ss.bind(new InetSocketAddress(IP, SERVERPORT)); // 新建socket通道的端口
Selector selector = Selector.open(); // 获取一个选择器
ssc.register(selector, SelectionKey.OP_ACCEPT); // 将NIO通道绑定到选择器,当然绑定后分配的主键为skey
// //////////////////////////////////////////////////////////////////
// //// 接收客户端的连接Socket,并将此Socket也接连注册到Selector ////
// /////////////////////////////////////////////////////////////////
while (true) {
int num = selector.selectNow(); // 获取通道内是否有选择器的关心事件
if (num < 1) continue;
Set selectedKeys = selector.selectedKeys();
Iterator it = selectedKeys.iterator();// 获取通道内关心事件的集合
while (it.hasNext()) { // 遍历每个事件
try {
SelectionKey key = (SelectionKey) it.next();
// 有一个新联接接入事件,服务端事件
if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
// 接收这个新连接
ServerSocketChannel serverChanel = (ServerSocketChannel) key.channel();
// 从serverSocketChannel中创建出与客户端的连接 socketChannel
SocketChannel sc