View Javadoc

    1   /*
    2    * Copyright 2012 The Netty Project
    3    *
    4    * The Netty Project licenses this file to you under the Apache License,
    5    * version 2.0 (the "License"); you may not use this file except in compliance
    6    * with the License. You may obtain a copy of the License at:
    7    *
    8    *   http://www.apache.org/licenses/LICENSE-2.0
    9    *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    13   * License for the specific language governing permissions and limitations
    14   * under the License.
    15   */
    16  //The MIT License
    17  //
    18  //Copyright (c) 2009 Carl Bystršm
    19  //
    20  //Permission is hereby granted, free of charge, to any person obtaining a copy
    21  //of this software and associated documentation files (the "Software"), to deal
    22  //in the Software without restriction, including without limitation the rights
    23  //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    24  //copies of the Software, and to permit persons to whom the Software is
    25  //furnished to do so, subject to the following conditions:
    26  //
    27  //The above copyright notice and this permission notice shall be included in
    28  //all copies or substantial portions of the Software.
    29  //
    30  //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    31  //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    32  //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    33  //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    34  //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    35  //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    36  //THE SOFTWARE.
    37  package org.jboss.netty.example.http.websocketx.client;
    38
    39  import java.net.InetSocketAddress;
    40  import java.net.URI;
    41  import java.util.HashMap;
    42  import java.util.concurrent.Executors;
    43
    44  import org.jboss.netty.bootstrap.ClientBootstrap;
    45  import org.jboss.netty.buffer.ChannelBuffers;
    46  import org.jboss.netty.channel.Channel;
    47  import org.jboss.netty.channel.ChannelFuture;
    48  import org.jboss.netty.channel.ChannelPipeline;
    49  import org.jboss.netty.channel.ChannelPipelineFactory;
    50  import org.jboss.netty.channel.Channels;
    51  import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
    52  import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
    53  import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
    54  import org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
    55  import org.jboss.netty.handler.codec.http.websocketx.PingWebSocketFrame;
    56  import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
    57  import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
    58  import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
    59  import org.jboss.netty.handler.codec.http.websocketx.WebSocketVersion;
    60
    61  public class WebSocketClient {
    62
    63      private final URI uri;
    64
    65      public WebSocketClient(URI uri) {
    66          this.uri = uri;
    67      }
    68
    69      public void run() throws Exception {
    70          ClientBootstrap bootstrap =
    71                  new ClientBootstrap(
    72                          new NioClientSocketChannelFactory(
    73                                  Executors.newCachedThreadPool(),
    74                                  Executors.newCachedThreadPool()));
    75
    76          Channel ch = null;
    77
    78          try {
    79              String protocol = uri.getScheme();
    80              if (!protocol.equals("ws")) {
    81                  throw new IllegalArgumentException("Unsupported protocol: " + protocol);
    82              }
    83
    84              HashMap<String, String> customHeaders = new HashMap<String, String>();
    85              customHeaders.put("MyHeader", "MyValue");
    86
    87              // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
    88              // If you change it to V00, ping is not supported and remember to change
    89              // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
    90              final WebSocketClientHandshaker handshaker =
    91                      new WebSocketClientHandshakerFactory().newHandshaker(
    92                              uri, WebSocketVersion.V13, null, false, customHeaders);
    93
    94              bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    95                  public ChannelPipeline getPipeline() throws Exception {
    96                      ChannelPipeline pipeline = Channels.pipeline();
    97
    98                      pipeline.addLast("decoder", new HttpResponseDecoder());
    99                      pipeline.addLast("encoder", new HttpRequestEncoder());
    100                     pipeline.addLast("ws-handler", new WebSocketClientHandler(handshaker));
    101                     return pipeline;
    102                 }
    103             });
    104
    105             // Connect
    106             System.out.println("WebSocket Client connecting");
    107             ChannelFuture future =
    108                     bootstrap.connect(
    109                             new InetSocketAddress(uri.getHost(), uri.getPort()));
    110             future.syncUninterruptibly();
    111
    112             ch = future.getChannel();
    113             handshaker.handshake(ch).syncUninterruptibly();
    114
    115             // Send 10 messages and wait for responses
    116             System.out.println("WebSocket Client sending message");
    117             for (int i = 0; i < 1000; i++) {
    118                 ch.write(new TextWebSocketFrame("Message #" + i));
    119             }
    120
    121             // Ping
    122             System.out.println("WebSocket Client sending ping");
    123             ch.write(new PingWebSocketFrame(ChannelBuffers.copiedBuffer(new byte[]{1, 2, 3, 4, 5, 6})));
    124
    125             // Close
    126             System.out.println("WebSocket Client sending close");
    127             ch.write(new CloseWebSocketFrame());
    128
    129             // WebSocketClientHandler will close the connection when the server
    130             // responds to the CloseWebSocketFrame.
    131             ch.getCloseFuture().awaitUninterruptibly();
    132         } finally {
    133             if (ch != null) {
    134                 ch.close();
    135             }
    136             bootstrap.releaseExternalResources();
    137         }
    138     }
    139
    140     public static void main(String[] args) throws Exception {
    141         URI uri;
    142         if (args.length > 0) {
    143             uri = new URI(args[0]);
    144         } else {
    145             uri = new URI("ws://localhost:8080/websocket");
    146         }
    147         new WebSocketClient(uri).run();
    148     }
    149 }