http协议header中,异步socket(nio、mina)中必须指定其Content-Length的长度,才算结束。
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.example.httpserver.stream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.support.BaseByteBuffer;
import org.apache.mina.filter.codec.ProtocolDecoderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.pica.common.CommonUtils;
import com.pica.config.Dispatch;
import com.pica.server.BaseAction;
import com.pica.server.Request;
import com.pica.server.action.FetchEventAction;
/**
* A simplistic HTTP protocol handler that replies back the URL and headers
* which a client requested.
*
* @author The Apache Directory Project (mina-dev@directory.apache.org)
* @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007)
* $
*/
public class HttpProtocolHandler extends IoHandlerAdapter {
private static final Logger Log = LoggerFactory.getLogger(HttpProtocolHandler.class);
public void sessionOpened(IoSession session) throws Exception {
Log.debug("ConnectionHandler: sessionOpened.");
}
@Override
public void sessionClosed(IoSession session) throws Exception {
Log.debug("ConnectionHandler: sessionClosed.");
}
/**
* Invoked when a MINA session has been idle for half of the allowed XMPP
* session idle time as specified by {@link #getMaxIdleTime()}. This method
* will be invoked each time that such a period passes (even if no IO has
* occurred in between).
*
* Openfire will disconnect a session the second time this method is
* invoked, if no IO has occurred between the first and second invocation.
* This allows extensions of this class to use the first invocation to check
* for livelyness of the MINA session (e.g by polling the remote entity, as
* {@link ClientConnectionHandler} does).
*
* 两次心跳时间内没有消息交互就断开连接
*
* @see org.apache.mina.common.IoHandlerAdapter#sessionIdle(org.apache.mina.common.IoSession,
* org.apache.mina.common.IdleStatus)
*/
@Override
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
// Close idle connection
Log.debug("ConnectionHandler:sessionIdle. Closing connection that has been idle: " + status);
}
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
if (cause instanceof IOException) {
Log.debug("ConnectionHandler: ", cause);
} else if (cause instanceof ProtocolDecoderException) {
Log.warn("Closing session due to exception: " + session, cause);
session.close();
} else {
Log.error(cause.getMessage(), cause);
}
}
public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
Log.debug(session.hashCode() + ":" + this.hashCode() + ":messageReceived:" + message.getClass() + "\t" + message);
org.apache.mina.common.support.BaseByteBuffer buffer = (org.apache.mina.common.support.BaseByteBuffer) message;
InputStream in = buffer.asInputStream();
String url;
Map<String, String> headers = new TreeMap<String, String>();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int timeout = 0;
StringBuffer sb = new StringBuffer();
try {
// Get request URL.
url = br.readLine();
if (url == null) {
Log.debug("nowTime:"+new Date().getTime());
Log.debug("getLastIoTime:"+session.getLastIoTime());
Log.debug("getLastReadTime:"+session.getLastReadTime());
Log.debug("getLastWriteTime:"+session.getLastWriteTime());
return;
}
url = url.split(" ")[1];
Log.debug("url:"+url);
String baseUrl = CommonUtils.getBaseUrl(url);
Log.debug("baseUrl:"+baseUrl);
if(baseUrl.endsWith("/aim/fetchEvents")){
baseUrl = "/aim/fetchEvents";
}
Map<String, String> parameter = CommonUtils.getParameter(url);
// Read header
String line;
while ((line = br.readLine()) != null && !line.equals("")) {
String[] tokens = line.replaceAll(" ", "").split(":");
headers.put(tokens[0], tokens[1]);
}
String zlass = Dispatch.getDispatch(baseUrl);
if (zlass != null) {
Object obj = Class.forName(zlass).newInstance();
if (obj instanceof BaseAction) {
BaseAction action = (BaseAction) obj;
timeout = action.doGet(new Request(in, headers, parameter), sb);
} else {
String notfound = "<html><head><title>Not Found</title></head><body><h1>Error 500-class [" + zlass + "] not extends com.pica.server.BaseAction</h1></body></html>";
sb.append("HTTP/1.0 500 Internal Server Error\n");
sb.append("Content_Type:text/html\n");
sb.append("Content-Length:"+notfound.getBytes().length+"\t");
sb.append("\r\n\r\n");
sb.append(notfound);
return;
}
} else {
String notfound = "<html><head><title>Not Found</title></head><body><h1>Error 404-file [" + url + "] not found</h1></body></html>";
sb.append("HTTP/1.0 404 no found\n");
sb.append("Content_Type:text/html\n");
sb.append("Content-Length:"+notfound.getBytes().length+"\t");
sb.append("\r\n\r\n");
sb.append(notfound);
return;
}
} catch (Exception e) {
sb.append("HTTP/1.0 500 Internal Server Error\n");
sb.append("Content_Type:text/html\n");
sb.append("Content-Length:"+e.getMessage().getBytes().length+"\t");
sb.append("\r\n\r\n");
sb.append(e.getMessage());
} finally {
//sb.append("\r\n\r\n");
if(timeout > 0){
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
session.write(BaseByteBuffer.wrap(sb.toString().getBytes()));
}
}
public void messageSent(IoSession session, Object message) throws Exception {
super.messageSent(session, message);
org.apache.mina.common.support.BaseByteBuffer buffer = (org.apache.mina.common.support.BaseByteBuffer) message;
InputStream in = buffer.asInputStream();
byte[] b = new byte[in.available()];
in.read(b);
Log.debug("###############################################################################################################");
Log.debug(session.hashCode() + ":" + this.hashCode() + ":messageSent:" + message.getClass() + "\t" + new String(b));
Log.debug("###############################################################################################################");
}
}
分享到:
相关推荐
本手册“Apache Mina Server 2.0中文参考手册V1.0”提供了对 Mina 2.0 版本的详细解析,旨在帮助开发者更好地理解和运用这个强大的工具。 Apache Mina 提供了一个统一的接口来处理多种类型的网络协议,如TCP/IP、...
这个压缩包“Apache_Mina_Server_2.0V1.0.rar_mina”包含了Apache Mina Server 2.0的中文参考手册,对于理解和使用Mina框架构建服务器端应用程序提供了详尽的指导。 Apache Mina的核心设计理念是提供一套统一的API...
Apache Mina Server是一款基于Java的高性能、可扩展的网络通信应用框架。它支持TCP/IP和UDP/IP协议栈通信,并且可以提供Java对象序列化服务、虚拟机管道通信服务等多种功能。Mina框架的核心设计思想是使用事件驱动、...
### Apache Mina Server深入教程V1.0 #### 一、Apache Mina Server简介 Apache Mina Server是一款高性能且易于使用的网络通信应用框架,主要基于TCP/IP和UDP/IP协议栈进行设计,同时也支持其他类型的通信服务,...
Apache Mina Server 2.0是一款强大的网络应用框架,它为开发者提供了构建高性能、高并发的网络服务的能力。这个框架的核心理念是简化网络通信的复杂性,让开发者能够专注于业务逻辑,而不是底层的网络协议实现。...
Apache Mina Server 深入教程 Apache Mina是一个开源项目,它提供了一个高度可扩展且性能优秀的网络通信框架,广泛应用于开发各种网络服务,如TCP/IP、UDP、HTTP等协议的服务端应用。本教程将深入探讨Apache Mina ...
Apache Mina Server 2.0 是一个高性能、可扩展的网络通信框架,广泛应用于开发网络应用服务器,如TCP/IP和UDP协议的服务器。这个中文参考手册V1.0旨在为开发者提供详细的指导,帮助他们更好地理解和使用Apache Mina ...
标题中的"Apache MINA Server 2.0"指的是MINA框架的一个特定版本,2.0版。在这个版本中,MINA可能引入了新的特性和性能优化,以满足不断发展的网络服务需求。MINA 2.0可能是对先前版本的改进,提高了稳定性和可扩展...
### Apache Mina Server 2.0 中文参考手册 V1.0 #### 一、Apache Mina Server 简介 Apache Mina Server 是一款强大的网络通信应用框架,旨在简化基于 TCP/IP 和 UDP/IP 协议栈的网络通信程序开发。它支持多种通信...
手册首先介绍了 Mina Server 的基本概念和架构,然后逐步引导开发者如何使用 Mina Server 来构建客户端和服务器端应用程序。对于想要建立 TCP 服务器(TCPServer)的开发者,手册中提供了简化的代码示例。 从技术...
### Apache Mina Server 2.0:网络通信框架的核心知识点 #### 一、Apache Mina Server简介 Apache Mina Server是一款高性能、可扩展的网络通信框架,主要针对基于TCP/IP和UDP/IP协议栈的通信需求。它不仅支持传统...
压缩包内的"Apache_Mina_Server_2.0中文参考手册V1.0.pdf"很可能是一个全面的指南,详细讲解了如何使用Apache Mina 2.0版本构建服务器端应用。手册中可能会包括如何设置服务器、定义协议、编写过滤器、处理事件、...
该资源是保存 虚无境 的博客 ...注意事项:源码是以GBK编码存储的,启动需要 把项目 Run as ServerApplication 之后 ,分别把MinaClient 和 MinaClientB run as Java Application ,才能达到消息推送效果
最后,`Apache_Mina_Server_2.0中文参考手册V1.0.pdf` 是MINA服务器端的中文参考手册,对于想要使用MINA构建服务器端应用的开发者来说尤其有用。这份手册可能详细解析了MINA服务器的搭建步骤、配置选项,以及如何...
深入理解Apache_Mina_(1)----_Mina的几个类 深入理解Apache_Mina_(2)----_与IoFilter相关的几个类 深入理解Apache_Mina_(3)----_与IoHandler相关的几个类 深入理解Apache_Mina_(4)----_IoFilter和IoHandler的区别和...