00001 #ifndef MYTHSOCKET_H
00002 #define MYTHSOCKET_H
00003
00004 #include <qsocketdevice.h>
00005 #include <qwaitcondition.h>
00006 #include <qtimer.h>
00007 #include <pthread.h>
00008 #include <qptrlist.h>
00009 #include "mythexp.h"
00010
00011 class QHostAddress;
00012 class MythSocket;
00013
00014 class MPUBLIC MythSocketCBs
00015 {
00016 public:
00017 virtual ~MythSocketCBs() {}
00018 virtual void connected(MythSocket*) = 0;
00019 virtual void readyRead(MythSocket*) = 0;
00020 virtual void connectionFailed(MythSocket*) = 0;
00021 virtual void connectionClosed(MythSocket*) = 0;
00022 };
00023
00024 class MPUBLIC MythSocket : public QSocketDevice
00025 {
00026 friend void readyReadThread_iffound(MythSocket*);
00027
00028 public:
00029 MythSocket(int socket = -1, MythSocketCBs *cb = NULL);
00030
00031 enum State {
00032 Connected,
00033 Connecting,
00034 HostLookup,
00035 Idle
00036 };
00037
00038 void close(void);
00039 void deleteLater(void);
00040
00041 void UpRef(void);
00042 bool DownRef(void);
00043
00044 State state(void);
00045 QString stateToString(void) { return stateToString(state()); }
00046 QString stateToString(const State state);
00047
00048 QString errorToString(void) { return errorToString(error()); }
00049 QString errorToString(const Error error);
00050
00051 void setSocket(int socket, Type type = QSocketDevice::Stream);
00052 void setCallbacks(MythSocketCBs *cb);
00053
00054 Q_LONG readBlock(char *data, Q_ULONG len);
00055 Q_LONG writeBlock(const char *data, Q_ULONG len);
00056
00057 bool readStringList(QStringList &list, bool quickTimeout = false);
00058 bool writeStringList(QStringList &list);
00059 bool writeData(const char *data, Q_ULONG len);
00060
00061 bool connect(const QHostAddress &addr, Q_UINT16 port);
00062 bool connect(const QString &host, Q_UINT16 port);
00063
00064 void Lock();
00065 void Unlock();
00066
00067 protected:
00068 ~MythSocket();
00069
00070 void setState(const State state);
00071
00072 MythSocketCBs *m_cb;
00073 State m_state;
00074 QHostAddress m_addr;
00075 Q_UINT16 m_port;
00076 int m_ref_count;
00077
00078 bool m_notifyread;
00079
00080 static const uint kSocketBufferSize;
00081
00082 QMutex m_ref_lock;
00083 QMutex m_lock;
00084
00085 static pthread_t m_readyread_thread;
00086 static bool m_readyread_run;
00087 static QMutex m_readyread_lock;
00088 static QPtrList<MythSocket> m_readyread_list;
00089 static QPtrList<MythSocket> m_readyread_dellist;
00090 static QPtrList<MythSocket> m_readyread_addlist;
00091 static int m_readyread_pipe[2];
00092
00093 static void StartReadyReadThread(void);
00094 static void *readyReadThread(void *);
00095
00096 static void AddToReadyRead(MythSocket *sock);
00097 static void RemoveFromReadyRead(MythSocket *sock);
00098 static void WakeReadyReadThread(void);
00099 static void ShutdownReadyReadThread(void);
00100
00101 friend class QPtrList<MythSocket>;
00102 };
00103
00104 #endif
00105