1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.http.helloworld;
17
18 import org.jboss.netty.buffer.ChannelBuffers;
19 import org.jboss.netty.channel.Channel;
20 import org.jboss.netty.channel.ChannelFuture;
21 import org.jboss.netty.channel.ChannelFutureListener;
22 import org.jboss.netty.channel.ChannelHandlerContext;
23 import org.jboss.netty.channel.Channels;
24 import org.jboss.netty.channel.ExceptionEvent;
25 import org.jboss.netty.channel.MessageEvent;
26 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
27 import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
28 import org.jboss.netty.handler.codec.http.HttpRequest;
29 import org.jboss.netty.handler.codec.http.HttpResponse;
30
31 import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*;
32 import static org.jboss.netty.handler.codec.http.HttpHeaders.*;
33 import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*;
34 import static org.jboss.netty.handler.codec.http.HttpVersion.*;
35
36 public class HttpHelloWorldServerHandler extends SimpleChannelUpstreamHandler {
37
38 private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };
39
40 @Override
41 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
42 Object msg = e.getMessage();
43 Channel ch = e.getChannel();
44 if (msg instanceof HttpRequest) {
45 HttpRequest req = (HttpRequest) msg;
46
47 if (is100ContinueExpected(req)) {
48 Channels.write(ctx, Channels.future(ch), new DefaultHttpResponse(HTTP_1_1, CONTINUE));
49 }
50
51 boolean keepAlive = isKeepAlive(req);
52 HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
53 response.setContent(ChannelBuffers.wrappedBuffer(CONTENT));
54 response.headers().set(CONTENT_TYPE, "text/plain");
55 response.headers().set(CONTENT_LENGTH, response.getContent().readableBytes());
56
57 if (!keepAlive) {
58 ChannelFuture f = Channels.future(ch);
59 f.addListener(ChannelFutureListener.CLOSE);
60 Channels.write(ctx, f, response);
61 } else {
62 response.headers().set(CONNECTION, Values.KEEP_ALIVE);
63 Channels.write(ctx, Channels.future(ch), response);
64 }
65 }
66 }
67
68 @Override
69 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
70 e.getCause().printStackTrace();
71 e.getChannel().close();
72 }
73 }