1/*
2 * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies)
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 * Library General Public License for more details.
13 *
14 * You should have received a copy of the GNU Library General Public License
15 * along with this program; see the file COPYING.LIB.  If not, write to
16 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
18 *
19 */
20
21
22#include "config.h"
23#include "WebSocketServerQt.h"
24
25#include "WebSocketServer.h"
26#include "WebSocketServerConnection.h"
27#include <WebCore/SocketStreamHandle.h>
28#include <wtf/PassOwnPtr.h>
29
30using namespace WebCore;
31
32namespace WebKit {
33
34void WebSocketServer::platformInitialize()
35{
36    m_tcpServerHandler = adoptPtr(new QtTcpServerHandler(this));
37}
38
39bool WebSocketServer::platformListen(const String& bindAddress, unsigned short port)
40{
41    return m_tcpServerHandler->listen(bindAddress, port);
42}
43
44void WebSocketServer::platformClose()
45{
46    m_tcpServerHandler->close();
47}
48
49QtTcpServerHandler::QtTcpServerHandler(WebSocketServer* webSocketServer)
50: m_webSocketServer(webSocketServer)
51{
52    connect(&m_serverSocket, SIGNAL(newConnection()), SLOT(handleNewConnection()));
53}
54
55void QtTcpServerHandler::handleNewConnection()
56{
57    QTcpSocket* socket = m_serverSocket.nextPendingConnection();
58    ASSERT(socket);
59    OwnPtr<WebSocketServerConnection> conection = adoptPtr(new WebSocketServerConnection(m_webSocketServer->client(), m_webSocketServer));
60    conection->setSocketHandle(SocketStreamHandle::create(socket, conection.get()));
61    m_webSocketServer->didAcceptConnection(conection.release());
62}
63
64bool QtTcpServerHandler::listen(const String& bindAddress, unsigned short port)
65{
66    ASSERT(!bindAddress.isEmpty());
67    ASSERT(port);
68    bool success = m_serverSocket.listen(QHostAddress(bindAddress), port);
69    if (!success)
70        LOG_ERROR("Can't open server socket on %s:%d [%s]", qPrintable(bindAddress), port, qPrintable(m_serverSocket.errorString()));
71    return success;
72}
73
74void QtTcpServerHandler::close()
75{
76    m_serverSocket.close();
77}
78
79}
80
81#include "moc_WebSocketServerQt.cpp"
82