我们在当前项目中使用Apache MINA进行TCP / IP协议,其中服务器和客户端通过TCP / IP进行通信。所以我们已经为MINA准备了一些代码。
现在我们也想支持http协议,并尽可能重用它。
我需要一些客户端/服务器代码示例,用于使用URL(/ servlet)连接MINA-HTTP。
我发现下面的链接 - http://mina.apache.org/report/trunk/xref/org/apache/mina/example/httpserver/codec/package-frame.html
但是寻找服务器和客户端的示例代码。 如果有人可以帮助我,这将是很好的
谢谢,
答案 0 :(得分:1)
final Object lock = new Object();
IoAcceptor acceptor = new NioSocketAcceptor();
((NioSocketAcceptor) acceptor).setReuseAddress(true);
acceptor.getFilterChain().addLast("httpServer", new HttpServerCodec());
acceptor.setHandler(new IoHandlerAdapter() {
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
// System.out.println("message "+message.getClass()+" "+message);
if (message instanceof HttpRequest) {
byte[] bytes = "Hello World!".getBytes();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Length", Integer.toString(bytes.length));
DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SUCCESS_OK,
headers);
session.write(resp);
session.write(IoBuffer.wrap(bytes));
session.write(new HttpEndOfContent());
if (((HttpRequest) message).getRequestPath().equals("/close")) {
synchronized (lock) {
lock.notify();
}
}
}
}
});
acceptor.bind(new InetSocketAddress(21212));
synchronized (lock) {
lock.wait();
}
acceptor.unbind();
acceptor.dispose(true);
答案 1 :(得分:1)
NioSocketAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast( "codec", new HttpServerCodec());
acceptor.setHandler(new IoHandlerAdapter() {
public void messageReceived(IoSession session, Object message)throws Exception {
if (message instanceof HttpRequestImpl) {
HttpRequestImpl request1 = (HttpRequestImpl) message;
}
if (message instanceof IoBuffer) {
SocketAddress addr = session.getRemoteAddress()
IoBuffer simbuf = (IoBuffer) message;
byte[] buff = simbuf.array();
String decoded = new String(buff, "UTF-8");
System.out.println(decoded);
}
if (message instanceof HttpEndOfContent) {
byte[] bytes = "OK".getBytes();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Length", Integer.toString(bytes.length));
DefaultHttpResponse resp = new DefaultHttpResponse(
HttpVersion.HTTP_1_1, HttpStatus.SUCCESS_OK, headers);
session.write(resp);
session.write(IoBuffer.wrap(bytes));
session.write(new HttpEndOfContent());
}
}
});
try {
acceptor.bind( new InetSocketAddress(1234) );
} catch (IOException e) {
e.printStackTrace();
}