1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 package org.jboss.netty.example.http.websocketx.client;
39
40 import org.jboss.netty.channel.Channel;
41 import org.jboss.netty.channel.ChannelHandlerContext;
42 import org.jboss.netty.channel.ChannelStateEvent;
43 import org.jboss.netty.channel.ExceptionEvent;
44 import org.jboss.netty.channel.MessageEvent;
45 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
46 import org.jboss.netty.handler.codec.http.HttpResponse;
47 import org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
48 import org.jboss.netty.handler.codec.http.websocketx.PingWebSocketFrame;
49 import org.jboss.netty.handler.codec.http.websocketx.PongWebSocketFrame;
50 import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
51 import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
52 import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame;
53 import org.jboss.netty.util.CharsetUtil;
54
55 public class WebSocketClientHandler extends SimpleChannelUpstreamHandler {
56
57 private final WebSocketClientHandshaker handshaker;
58
59 public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
60 this.handshaker = handshaker;
61 }
62
63 @Override
64 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
65 System.out.println("WebSocket Client disconnected!");
66 }
67
68 @Override
69 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
70 Channel ch = ctx.getChannel();
71 if (!handshaker.isHandshakeComplete()) {
72 handshaker.finishHandshake(ch, (HttpResponse) e.getMessage());
73 System.out.println("WebSocket Client connected!");
74 return;
75 }
76
77 if (e.getMessage() instanceof HttpResponse) {
78 HttpResponse response = (HttpResponse) e.getMessage();
79 throw new Exception("Unexpected HttpResponse (status=" + response.getStatus() + ", content="
80 + response.getContent().toString(CharsetUtil.UTF_8) + ')');
81 }
82
83 WebSocketFrame frame = (WebSocketFrame) e.getMessage();
84 if (frame instanceof TextWebSocketFrame) {
85 TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
86 System.out.println("WebSocket Client received message: " + textFrame.getText());
87 } else if (frame instanceof PongWebSocketFrame) {
88 System.out.println("WebSocket Client received pong");
89 } else if (frame instanceof CloseWebSocketFrame) {
90 System.out.println("WebSocket Client received closing");
91 ch.close();
92 } else if (frame instanceof PingWebSocketFrame) {
93 System.out.println("WebSocket Client received ping, response with pong");
94 ch.write(new PongWebSocketFrame(frame.getBinaryData()));
95 }
96 }
97
98 @Override
99 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
100 final Throwable t = e.getCause();
101 t.printStackTrace();
102 e.getChannel().close();
103 }
104 }