• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 #ifndef _SOCKETLISTENER_H
17 #define _SOCKETLISTENER_H
18 
19 #include <pthread.h>
20 
21 #include <unordered_map>
22 
23 #include <sysutils/SocketClient.h>
24 #include "SocketClientCommand.h"
25 
26 class SocketListener {
27     bool                    mListen;
28     const char              *mSocketName;
29     int                     mSock;
30     std::unordered_map<int, SocketClient*> mClients;
31     pthread_mutex_t         mClientsLock;
32     int                     mCtrlPipe[2];
33     pthread_t               mThread;
34     bool                    mUseCmdNum;
35 
36 public:
37     SocketListener(const char *socketName, bool listen);
38     SocketListener(const char *socketName, bool listen, bool useCmdNum);
39     SocketListener(int socketFd, bool listen);
40 
41     virtual ~SocketListener();
42     int startListener();
43     int startListener(int backlog);
44     int stopListener();
45 
46     void sendBroadcast(int code, const char *msg, bool addErrno);
47 
48     void runOnEachSocket(SocketClientCommand *command);
49 
release(SocketClient * c)50     bool release(SocketClient *c) { return release(c, true); }
51 
52 protected:
53     virtual bool onDataAvailable(SocketClient *c) = 0;
54 
55 private:
56     static void *threadStart(void *obj);
57 
58     // Add all clients to a separate list, so we don't have to hold the lock
59     // while processing it.
60     std::vector<SocketClient*> snapshotClients();
61 
62     bool release(SocketClient *c, bool wakeup);
63     void runListener();
64     void init(const char *socketName, int socketFd, bool listen, bool useCmdNum);
65 };
66 #endif
67