Home | History | Annotate | Download | only in ws
      1 /*
      2  * Copyright (C) 2014 Square, Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * 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,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package com.squareup.okhttp.ws;
     17 
     18 import java.io.IOException;
     19 import okio.Buffer;
     20 import okio.BufferedSink;
     21 
     22 /** Blocking interface to connect and write to a web socket. */
     23 public interface WebSocket {
     24   /** The format of a message payload. */
     25   enum PayloadType {
     26     /** UTF8-encoded text data. */
     27     TEXT,
     28     /** Arbitrary binary data. */
     29     BINARY
     30   }
     31 
     32   /**
     33    * Stream a message payload to the server of the specified {code type}.
     34    * <p>
     35    * You must call {@link BufferedSink#close() close()} to complete the message. Calls to
     36    * {@link BufferedSink#flush() flush()} write a frame fragment. The message may be empty.
     37    *
     38    * @throws IllegalStateException if not connected, already closed, or another writer is active.
     39    */
     40   BufferedSink newMessageSink(WebSocket.PayloadType type);
     41 
     42   /**
     43    * Send a message payload to the server of the specified {@code type}.
     44    *
     45    * @throws IllegalStateException if not connected, already closed, or another writer is active.
     46    */
     47   void sendMessage(WebSocket.PayloadType type, Buffer payload) throws IOException;
     48 
     49   /**
     50    * Send a ping to the server with optional payload.
     51    *
     52    * @throws IllegalStateException if already closed.
     53    */
     54   void sendPing(Buffer payload) throws IOException;
     55 
     56   /**
     57    * Send a close frame to the server.
     58    * <p>
     59    * The corresponding {@link WebSocketListener} will continue to get messages until its
     60    * {@link WebSocketListener#onClose onClose()} method is called.
     61    * <p>
     62    * It is an error to call this method before calling close on an active writer. Calling this
     63    * method more than once has no effect.
     64    *
     65    * @throws IllegalStateException if already closed.
     66    */
     67   void close(int code, String reason) throws IOException;
     68 }
     69