Add initial support for a declarative WebSocketServer.
[contrib/qtwebsockets.git] / src / imports / qmlwebsockets / qqmlwebsocket.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights.  These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file.  Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 /*!
43     \qmltype WebSocket
44     \instantiates QQmlWebSocket
45
46     \inqmlmodule Qt.WebSockets
47     \ingroup websockets-qml
48     \brief QML interface to QWebSocket.
49
50     WebSockets is a web technology providing full-duplex communications channels over a
51     single TCP connection.
52     The WebSocket protocol was standardized by the IETF as
53     \l {http://tools.ietf.org/html/rfc6455} {RFC 6455} in 2011.
54 */
55
56 /*!
57   \qmlproperty QUrl WebSocket::url
58   Server url to connect to. The url must have one of 2 schemes: \e ws:// or \e wss://.
59   When not supplied, then \e ws:// is used.
60   */
61
62 /*!
63   \qmlproperty Status WebSocket::status
64   Status of the WebSocket.
65
66   The status can have the following values:
67   \list
68   \li WebSockets.Connecting
69   \li WebSockets.Open
70   \li WebSockets.Closing
71   \li WebSockets.Closed
72   \li WebSockets.Error
73   \endlist
74   */
75
76 /*!
77   \qmlproperty QString WebSocket::errorString
78   Contains a description of the last error that occurred. When no error occurrred,
79   this string is empty.
80   */
81
82 /*!
83   \qmlproperty bool WebSocket::active
84   When set to true, a connection is made to the server with the given url.
85   When set to false, the connection is closed.
86   The default value is false.
87   */
88
89 /*!
90   \qmlsignal WebSocket::textMessageReceived(QString message)
91   This signal is emitted when a text message is received.
92   */
93
94 /*!
95   \qmlsignal WebSocket::statusChanged(Status status)
96   This signal is emitted when the status of the WebSocket changes.
97   the \l {WebSocket::status}{status} argument provides the current status.
98
99   \sa WebSocket::status
100   */
101
102 /*!
103   \qmlmethod void WebSocket::sendTextMessage(string message)
104   Sends \c message to the server.
105   */
106
107 #include "qqmlwebsocket.h"
108 #include <QtWebSockets/QWebSocket>
109
110 QT_BEGIN_NAMESPACE
111
112 QQmlWebSocket::QQmlWebSocket(QObject *parent) :
113     QObject(parent),
114     m_webSocket(),
115     m_status(Closed),
116     m_url(),
117     m_isActive(false),
118     m_componentCompleted(true),
119     m_errorString()
120 {
121 }
122
123 QQmlWebSocket::QQmlWebSocket(QWebSocket *socket, QObject *parent) :
124     QObject(parent),
125     m_status(Closed),
126     m_url(socket->requestUrl()),
127     m_isActive(true),
128     m_componentCompleted(true),
129     m_errorString(socket->errorString())
130 {
131     setSocket(socket);
132     onStateChanged(socket->state());
133 }
134
135 QQmlWebSocket::~QQmlWebSocket()
136 {
137 }
138
139 qint64 QQmlWebSocket::sendTextMessage(const QString &message)
140 {
141     if (m_status != Open) {
142         setErrorString(tr("Messages can only be sent when the socket is open."));
143         setStatus(Error);
144         return 0;
145     }
146     return m_webSocket->sendTextMessage(message);
147 }
148
149 QUrl QQmlWebSocket::url() const
150 {
151     return m_url;
152 }
153
154 void QQmlWebSocket::setUrl(const QUrl &url)
155 {
156     if (m_url == url) {
157         return;
158     }
159     if (m_webSocket && (m_status == Open)) {
160         m_webSocket->close();
161     }
162     m_url = url;
163     Q_EMIT urlChanged();
164     if (m_webSocket) {
165         m_webSocket->open(m_url);
166     }
167 }
168
169 QQmlWebSocket::Status QQmlWebSocket::status() const
170 {
171     return m_status;
172 }
173
174 QString QQmlWebSocket::errorString() const
175 {
176     return m_errorString;
177 }
178
179 void QQmlWebSocket::classBegin()
180 {
181     m_componentCompleted = false;
182     m_errorString = tr("QQmlWebSocket is not ready.");
183     m_status = Closed;
184 }
185
186 void QQmlWebSocket::componentComplete()
187 {
188     setSocket(new QWebSocket);
189
190     m_componentCompleted = true;
191
192     open();
193 }
194
195 void QQmlWebSocket::setSocket(QWebSocket *socket)
196 {
197     m_webSocket.reset(socket);
198     if (m_webSocket) {
199         // explicit ownership via QScopedPointer
200         m_webSocket->setParent(Q_NULLPTR);
201         connect(m_webSocket.data(), &QWebSocket::textMessageReceived,
202                 this, &QQmlWebSocket::textMessageReceived);
203         typedef void (QWebSocket::* ErrorSignal)(QAbstractSocket::SocketError);
204         connect(m_webSocket.data(), static_cast<ErrorSignal>(&QWebSocket::error),
205                 this, &QQmlWebSocket::onError);
206         connect(m_webSocket.data(), &QWebSocket::stateChanged,
207                 this, &QQmlWebSocket::onStateChanged);
208     }
209 }
210
211 void QQmlWebSocket::onError(QAbstractSocket::SocketError error)
212 {
213     Q_UNUSED(error)
214     setErrorString(m_webSocket->errorString());
215     setStatus(Error);
216 }
217
218 void QQmlWebSocket::onStateChanged(QAbstractSocket::SocketState state)
219 {
220     switch (state)
221     {
222         case QAbstractSocket::ConnectingState:
223         case QAbstractSocket::BoundState:
224         case QAbstractSocket::HostLookupState:
225         {
226             setStatus(Connecting);
227             break;
228         }
229         case QAbstractSocket::UnconnectedState:
230         {
231             setStatus(Closed);
232             break;
233         }
234         case QAbstractSocket::ConnectedState:
235         {
236             setStatus(Open);
237             break;
238         }
239         case QAbstractSocket::ClosingState:
240         {
241             setStatus(Closing);
242             break;
243         }
244         default:
245         {
246             setStatus(Connecting);
247             break;
248         }
249     }
250 }
251
252 void QQmlWebSocket::setStatus(QQmlWebSocket::Status status)
253 {
254     if (m_status == status) {
255         return;
256     }
257     m_status = status;
258     if (status != Error) {
259         setErrorString();
260     }
261     Q_EMIT statusChanged(m_status);
262 }
263
264 void QQmlWebSocket::setActive(bool active)
265 {
266     if (m_isActive == active) {
267         return;
268     }
269     m_isActive = active;
270     Q_EMIT activeChanged(m_isActive);
271     if (!m_componentCompleted) {
272         return;
273     }
274     if (m_isActive) {
275         open();
276     } else {
277         close();
278     }
279 }
280
281 bool QQmlWebSocket::isActive() const
282 {
283     return m_isActive;
284 }
285
286 void QQmlWebSocket::open()
287 {
288     if (m_componentCompleted && m_isActive && m_url.isValid() && Q_LIKELY(m_webSocket)) {
289         m_webSocket->open(m_url);
290     }
291 }
292
293 void QQmlWebSocket::close()
294 {
295     if (m_componentCompleted && Q_LIKELY(m_webSocket)) {
296         m_webSocket->close();
297     }
298 }
299
300 void QQmlWebSocket::setErrorString(QString errorString)
301 {
302     if (m_errorString == errorString) {
303         return;
304     }
305     m_errorString = errorString;
306     Q_EMIT errorStringChanged(m_errorString);
307 }
308
309 QT_END_NAMESPACE