1 /* 2 * Copyright (C) 2019 The Android Open Source Project 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 17 #pragma once 18 19 #include <arpa/inet.h> 20 #include <cstdint> 21 #include <functional> 22 #include <memory> 23 #include <string> 24 #include <sys/types.h> 25 26 struct ClientSocket; 27 28 struct WebSocketHandler { 29 virtual ~WebSocketHandler() = default; 30 31 // Returns number bytes processed or error. 32 ssize_t handleRequest(uint8_t *data, size_t size, bool isEOS); 33 34 bool isConnected(); 35 36 virtual void setClientSocket(std::weak_ptr<ClientSocket> client); 37 38 typedef std::function<void(const uint8_t *, size_t)> OutputCallback; 39 void setOutputCallback(const sockaddr_in &remoteAddr, OutputCallback fn); 40 41 enum class SendMode { 42 text, 43 binary, 44 closeConnection, 45 }; 46 int sendMessage( 47 const void *data, size_t size, SendMode mode = SendMode::text); 48 49 std::string remoteHost() const; 50 51 protected: 52 virtual int handleMessage( 53 uint8_t headerByte, const uint8_t *msg, size_t len) = 0; 54 55 private: 56 std::weak_ptr<ClientSocket> mClientSocket; 57 58 OutputCallback mOutputCallback; 59 sockaddr_in mRemoteAddr; 60 }; 61