1 //
2 // ========================================================================
3 // Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
8 //
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
11 //
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
14 //
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
17 //
18
19 package org.eclipse.jetty.websocket.api.io;
20
21 import java.io.IOException;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.Future;
24
25 import javax.net.websocket.SendResult;
26
27 import org.eclipse.jetty.websocket.api.WebSocketConnection;
28 import org.eclipse.jetty.websocket.api.WebSocketException;
29
30 /**
31 * For working with the {@link WebSocketConnection} in a blocking technique.
32 * <p>
33 * This is an end-user accessible class.
34 */
35 public class WebSocketBlockingConnection
36 {
37 private final WebSocketConnection conn;
38
39 public WebSocketBlockingConnection(WebSocketConnection conn)
40 {
41 this.conn = conn;
42 }
43
44 /**
45 * Send a binary message.
46 * <p>
47 * Basic usage, results in a blocking write.
48 */
49 public void write(byte[] data, int offset, int length) throws IOException
50 {
51 try
52 {
53 Future<SendResult> blocker = conn.write(data,offset,length);
54 SendResult result = blocker.get(); // block till finished
55 if (result.getException() != null)
56 {
57 throw new WebSocketException(result.getException());
58 }
59 }
60 catch (InterruptedException e)
61 {
62 throw new IOException("Blocking write failed",e);
63 }
64 catch (ExecutionException e)
65 {
66 throw new WebSocketException(e.getCause());
67 }
68 }
69
70 /**
71 * Send text message.
72 * <p>
73 * Basic usage, results in a blocking write.
74 */
75 public void write(String message) throws IOException
76 {
77 try
78 {
79 Future<SendResult> blocker = conn.write(message);
80 SendResult result = blocker.get(); // block till finished
81 if (result.getException() != null)
82 {
83 throw new WebSocketException(result.getException());
84 }
85 }
86 catch (InterruptedException e)
87 {
88 throw new IOException("Blocking write failed",e);
89 }
90 catch (ExecutionException e)
91 {
92 throw new WebSocketException(e.getCause());
93 }
94 }
95 }