/** * * @param byteBuffer */ public void read(ByteBuffer byteBuffer){ try { int length = available(); if(length > byteBuffer.remaining()){ length = byteBuffer.remaining(); } byte[] bytes = new byte[length]; socket.getInputStream().read(bytes, 0, length); byteBuffer.put(bytes); lastReadTime = System.currentTimeMillis(); } catch (IOException e) { //after a few millsecond use part use receive a close event; close(TcpConnectionCloseReason.WriteError); } } /**
public void onRead(TcpConnection connection){ if(connection.packet == null){ connection.packet = new HttpResponse(); } HttpResponse response = (HttpResponse)connection.packet; ByteBuffer byteBuffer = ByteBuffer.allocate(connection.available()); connection.read(byteBuffer); byteBuffer.flip(); HttpResponse result = null; try { result = HttpSerializeUtils.deSerialize(byteBuffer, response); } catch (HttpParseException e) { connection.close(HttpResponseStatus.phraseMap.get(HttpResponseStatus.BAD_REQUEST));// } HttpContext context = httpContexts.get(connection); connection.packet = null; httpClientHandler.onHttpResponse(result, context); } public void onReadIdle(TcpConnection connection) {
/** * * @param closeReason */ public void close(String closeReason) { connection.close(closeReason); } }
public void onRead(TcpConnection connection){ //create packet if not create before if(connection.packet == null){ connection.packet = new HttpRequest(); } HttpRequest request = (HttpRequest)connection.packet; //read all data from connection ByteBuffer byteBuffer = ByteBuffer.allocate(connection.available()); connection.read(byteBuffer); byteBuffer.flip(); try { HttpRequest request2 = HttpSerializeUtils.deSerialize(byteBuffer, request); //判断是否解析完成 if(request2 != null){ HttpContext context = httpContexts.get(connection); httpServerHandler.onHttpRequest(request, context); connection.packet = null; } } catch (HttpParseException e) { e.printStackTrace(); sendErrorAndCloseConnection(connection, HttpResponseStatus.BAD_REQUEST); } }
public void run() { while(true){ try { Socket socket = accepter.accept(); if(socket != null){ TcpConnection connection = new TcpConnection(socket); //if exceed maxConnectionCount if(maxConnectionCount!=0 && getConnections().size()>= maxConnectionCount){ connection.close(TcpConnectionCloseReason.ExceedMaxConnectionCount); continue; } connection.inReading = false; connection.lastReadTime = System.currentTimeMillis(); connectionManager.add(connection); } }catch (Exception e) { //open too many file or accepter be close e.printStackTrace(); break; } } } };
/** * * @param connection * @param request */ static public void writeHttpRequest(TcpConnection connection, HttpRequest request){ ByteBuffer byteBuffer = HttpSerializeUtils.serialize(request); byteBuffer.flip(); connection.writeAndFlush(byteBuffer); } /**
/** * * @param ip * @param port * @param count * @param createGap * @param ioHandler * @throws IOException */ public void start(String ip,int port,int count,int createGap,IoHandler ioHandler)throws IOException{ connectionManager.start(ioHandler); this.lastCreateTime = System.currentTimeMillis(); //generate connection while(count > 0){ if(System.currentTimeMillis() - lastCreateTime> createGap){ count--; lastCreateTime += createGap; /** * general with nuli threads ,will get connect error and efficiency not up */ Socket socket = new Socket(ip,port); TcpConnection connection = new TcpConnection(socket); connectionManager.add(connection); } } }
public void run() { while(true){ long time = System.currentTimeMillis(); ArrayList<TcpConnection> connections = getConnections(); synchronized (connections) { /** * 如果连接列表中存在某个connection,说明他还没有关闭,在这里加超时事件一定会该连接的关闭时间之前; */ for (int i = 0; i < getConnections().size(); i++) { TcpConnection connection = connections.get(i); if(readIdleTimeoutSeconds !=0 &&connection.isClose() == false&&time - connection.lastReadTime> readIdleTimeoutSeconds*1000){ //use part will receive a close event; ioHandler.onReadIdle(connection); } } } try { Thread.sleep(readIdleCheckGapSeconds); } catch (InterruptedException e) { break; } } } };
public void onReadIdle(TcpConnection connection) { connection.close(TcpConnectionCloseReason.ReadIdleTimeOut); } public void onClose(TcpConnection connection, String reason){
/** * * @param connection * @param response */ static public void writeHttpResponse(TcpConnection connection, HttpResponse response){ ByteBuffer byteBuffer = HttpSerializeUtils.serialize(response); byteBuffer.flip(); connection.writeAndFlush(byteBuffer); } }
public void onReadIdle(TcpConnection connection) { connection.close(TcpConnectionCloseReason.ReadIdleTimeOut); }
/** * * @return */ public int available(){ int available = 0; try { available = socket.getInputStream().available(); } catch (IOException e) { close(TcpConnectionCloseReason.ReadError); } return available; } /**
/** * * @param byteBuffer */ public void writeAndFlush(ByteBuffer byteBuffer){ // byteBuffer.flip(); byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); try { socket.getOutputStream().write(bytes); socket.getOutputStream().flush(); } catch (IOException e) { //after a few millsecond use part use receive a close event; close(TcpConnectionCloseReason.WriteError); } } /**
private void sendErrorAndCloseConnection(TcpConnection connection,int responseStatus){ HttpResponse response = new HttpResponse(); response.status = HttpResponseStatus.BAD_REQUEST; response.phrase = HttpResponseStatus.phraseMap.get(response.status); response.content = ("errorcode="+response.phrase).getBytes(); HttpConnectionUtils.writeHttpResponse(connection, response); connection.close(response.phrase); }
/** * */ public void shutdown(){ //stop all thread checkSocketStatusThread.interrupt(); distributionTaskThread.interrupt(); while(true){ if(checkSocketStatusThread.isAlive() != false||distributionTaskThread.isAlive() != false){ break; } } while(true){ //keep started task normal complete if(((ThreadPoolExecutor)exeTaskThreads).getActiveCount()==0){ exeTaskThreads.shutdown(); break; } } synchronized (connections) { for (int i = 0; i < connections.size(); i++) { connections.get(i).close(TcpConnectionCloseReason.ShutDownTcpConnectionManager); } connections.clear(); } //clear connection and task; tasks.clear(); } /**