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 */ 16package com.squareup.okhttp.ws; 17 18import com.squareup.okhttp.MediaType; 19import com.squareup.okhttp.RequestBody; 20import java.io.IOException; 21import okio.Buffer; 22 23/** Blocking interface to connect and write to a web socket. */ 24public interface WebSocket { 25 /** A {@link MediaType} indicating UTF-8 text frames should be used when sending the message. */ 26 MediaType TEXT = MediaType.parse("application/vnd.okhttp.websocket+text; charset=utf-8"); 27 /** A {@link MediaType} indicating binary frames should be used when sending the message. */ 28 MediaType BINARY = MediaType.parse("application/vnd.okhttp.websocket+binary"); 29 30 /** 31 * Send a message payload to the server. 32 * 33 * <p>The {@linkplain RequestBody#contentType() content type} of {@code message} should be either 34 * {@link #TEXT} or {@link #BINARY}. 35 * 36 * @throws IOException if unable to write the message. Clients must call {@link #close} when this 37 * happens to ensure resources are cleaned up. 38 * @throws IllegalStateException if not connected, already closed, or another writer is active. 39 */ 40 void sendMessage(RequestBody message) throws IOException; 41 42 /** 43 * Send a ping to the server with optional payload. 44 * 45 * @throws IOException if unable to write the ping. Clients must call {@link #close} when this 46 * happens to ensure resources are cleaned up. 47 * @throws IllegalStateException if already closed. 48 */ 49 void sendPing(Buffer payload) throws IOException; 50 51 /** 52 * Send a close frame to the server. 53 * <p> 54 * The corresponding {@link WebSocketListener} will continue to get messages until its 55 * {@link WebSocketListener#onClose onClose()} method is called. 56 * <p> 57 * It is an error to call this method before calling close on an active writer. Calling this 58 * method more than once has no effect. 59 * 60 * @throws IOException if unable to write the close message. Resources will still be freed. 61 * @throws IllegalStateException if already closed. 62 */ 63 void close(int code, String reason) throws IOException; 64} 65