コード例 #1
0
ファイル: mrimconnection.cpp プロジェクト: reindeer/qutim
void MrimConnection::connected()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    Q_ASSERT(socket);
	SystemIntegration::keepAlive(socket);

    bool connected = false;

    switch (socket->state())
    {
    case QAbstractSocket::ConnectedState:
        connected = true;
        break;
    default:
        break;
    }

    QString address = Utils::toHostPortPair(socket->peerAddress(),socket->peerPort());

    if (!connected)
    {
        debug()<<"Connection to server"<<qPrintable(address)<<"failed! :(";
        return;
    }
    else
    {
        debug()<<"Connected to server"<<qPrintable(address);

        if (socket == p->IMSocket()) //temp
        {
            sendGreetings();
        }
    }
}
コード例 #2
0
ファイル: Server.cpp プロジェクト: ocmwdt/usbwatcher
void Server::sendResponse() {
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

    stringstream peerStream;
    peerStream << clientConnection->peerAddress().toString().toStdString()
            << ":"
            << clientConnection->peerPort();
    string peer = peerStream.str();

    if (clientConnection->waitForReadyRead(10000)) {
        clientConnection->readLine(readBuffer, BUFFER_LEN);
        string message(readBuffer);
        string deviceId = "";

        if (message.length() > 4) {
            deviceId = message.substr(4);
        }

        if (message.find("GET ", 0, 4) == 0) {
            string response = processGetOpertion(peer, deviceId);
            clientConnection->write(response.c_str());
        } else if (message.find("ADD ", 0, 4) == 0) {
            bool added = processAddOpertion(deviceId);
            if (added) {
                clientConnection->write("ADDED");
            } else {
                clientConnection->write("NOT ADDED");
            }
        }
    }
    clientConnection->disconnectFromHost();
}
コード例 #3
0
ファイル: serverskt.cpp プロジェクト: sdlylshl/sokit
void ServerSktTcp::newConnection()
{
	QTcpServer* server = qobject_cast<QTcpServer*>(sender());
	if (!server) return;

	QTcpSocket* client = server->nextPendingConnection();
	while (client)
	{
		Conn* conn = new Conn;
		if (!conn)
		{
			client->deleteLater();
		}
		else
		{
			client->setProperty(PROP_CONN, qVariantFromValue((void*)conn));

			conn->client = client;
			conn->key = TK::ipstr(client->peerAddress(),client->peerPort(), true);

			connect(client, SIGNAL(readyRead()), this, SLOT(newData()));
			connect(client, SIGNAL(destroyed(QObject*)), this, SLOT(close(QObject*)));
			connect(client, SIGNAL(disconnected()), client, SLOT(deleteLater()));
			connect(client, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error()));

			setCookie(conn->key, conn);
		}
		client = server->nextPendingConnection();
	}
}
コード例 #4
0
ファイル: chatserver.cpp プロジェクト: osamu-k/qt_study_osaka
void ChatServer::socketDisconnected()
{
    qDebug() << "socket disconnected";
    QTcpSocket *senderSocket = qobject_cast<QTcpSocket *>(sender());
    QString address = senderSocket->peerAddress().toString();
    quint16 port = senderSocket->peerPort();

    m_socketList.removeAll(senderSocket);
    emit disconnected(address, port);
}
コード例 #5
0
ファイル: spotifyserver.cpp プロジェクト: BrummbQ/Clementine
void SpotifyServer::NewConnection() {
  QTcpSocket* socket = server_->nextPendingConnection();
  SetDevice(socket);

  qLog(Info) << "Connection from port" << socket->peerPort();

  // Send any login messages that were queued before the client connected
  foreach (const pb::spotify::Message& message, queued_login_messages_) {
    SendOrQueueMessage(message);
  }
コード例 #6
0
void ConnectionThread::run()
{
    Debug() << "Thread started.";
    QTcpSocket sock;
    socketNoNagle(sockdescr);
    if (!sock.setSocketDescriptor(sockdescr)) {
        Error() << sock.errorString();
        return;
    }
    QString remoteHostPort = sock.peerAddress().toString() + ":" + QString::number(sock.peerPort());
    Log() << "Connection from peer " << remoteHostPort;
    QString line;
    forever {
        if (sock.canReadLine() || sock.waitForReadyRead()) {
            line = sock.readLine().trimmed();
            while (StimApp::instance()->busy()) {
                // special case case, stimapp is busy so keep polling with 1s intervals                
                Debug() << "StimApp busy, cannot process command right now.. trying again in 1 second";
                sleep(1); // keep sleeping 1 second until the stimapp is no longer busy .. this keeps us from getting given commands while we are still initializing
            }
            // normal case case, stimapp not busy,  proceed normally
            QString resp;
            resp = processLine(sock, line);
            if (sock.state() != QAbstractSocket::ConnectedState) {
                Debug() << "processLine() closed connection";
                break;
            }
            if (!resp.isNull()) {
                if (resp.length()) {
                    Debug() << "Sending: " << resp;
                    if (!resp.endsWith("\n")) resp += "\n";
					QByteArray data(resp.toUtf8());
                    int len = sock.write(data);
					if (len != data.length()) {
						Debug() << "Sent "  << len << " bytes but expected to send " << data.length() << " bytes!";
					}
                }
                Debug() << "Sending: OK";
                sock.write("OK\n");
            } else {
                Debug() << "Sending: ERROR";
                sock.write("ERROR\n");
            }            
        } else {
            if (sock.error() != QAbstractSocket::SocketTimeoutError 
                || sock.state() != QAbstractSocket::ConnectedState) {
                Debug() << "Socket error: " << sock.error() << " Socket state: " << sock.state();
                break;
            }
        }
    }
    Log() << "Connection ended (peer: " << remoteHostPort << ")";
    Debug() << "Thread exiting.";
}
コード例 #7
0
ファイル: SyncServer.cpp プロジェクト: mitranog/syncsmith
void SyncServer::OnNewConnection()
{
    QTcpSocket* newClient = mServer.nextPendingConnection();
    QString peerName = newClient->peerAddress().toString() + ":" + QString::number(newClient->peerPort());
    Q_ASSERT(mClients.find(peerName) == mClients.end()); // Make sure this user doesn't already exist
    SyncClient* syncClient = new SyncClient(newClient);
    mClients[peerName] = syncClient;

    connect(syncClient, &SyncClient::Disconnected, this, &SyncServer::OnClientDisconnected);
    connect(syncClient, &SyncClient::PacketReceived, this, &SyncServer::OnPacketReceived);

    qDebug() << "Client '" << peerName << "' Connected.";
}
コード例 #8
0
void Manager::registerSocket()
{
    ++clientsConnected;
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    reportStatus();
    Q_EMIT message(tr("Client %1(%2) connected.")
                   .arg(clientConnection->peerAddress().toString())
                   .arg(clientConnection->peerPort()));
    connect(clientConnection, SIGNAL(disconnected()),
            this, SLOT(clearSocket()));
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readRequest()));
    connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));
}
コード例 #9
0
ファイル: chatserver.cpp プロジェクト: osamu-k/qt_study_osaka
void ChatServer::serverNewConnection()
{
    qDebug() << "new connection";
    while( m_server->hasPendingConnections() ){
        QTcpSocket *socket = m_server->nextPendingConnection();
        QString address = socket->peerAddress().toString();
        quint16 port = socket->peerPort();

        connect(socket, &QTcpSocket::readyRead, this, &ChatServer::socketReadyRead);
        connect(socket,&QTcpSocket::disconnected, this, &ChatServer::socketDisconnected);

        m_socketList << socket;
        emit connected(address, port);
    }
}
コード例 #10
0
void SpotifyServer::NewConnection() {
  QTcpSocket* socket = server_->nextPendingConnection();
  SetDevice(socket);

  qLog(Info) << "Connection from port" << socket->peerPort();

  // Send any login messages that were queued before the client connected
  for (const pb::spotify::Message& message : queued_login_messages_) {
    SendOrQueueMessage(message);
  }
  queued_login_messages_.clear();

  // Don't take any more connections from clients
  disconnect(server_, SIGNAL(newConnection()), this, 0);
}
コード例 #11
0
ファイル: TcpServer.cpp プロジェクト: PonyYu/OCR_LIVE_HISTORY
/**
 *函数介绍:跟踪server端socket状态
 *输入参数:服务端socket状态
 *返回值:无
 */
void TcpServer::getServerSocketState(QAbstractSocket::SocketState socketState)
{
	QTcpSocket *serverSocket = qobject_cast<QTcpSocket *>(sender());
	QString clientIp = serverSocket->peerAddress().toString();
	int clientPort = serverSocket->peerPort();
	QString serverIp = this->serverAddress().toString();
	int serverPort = this->serverPort();
	//测试代码  是否和上面的一样的Ip和port???
	QString serverIp1 = serverSocket->localAddress().toString();
	int serverPort1 = serverSocket->localPort();
	//测试代码
    switch (socketState)
    {
    case QAbstractSocket::UnconnectedState: 
		qDebug() << "服务端:UnconnectedState:The socket is not connected.";
		//Global::systemLog->append(QString(tr("网络服务端状态:断开连接状态,未连上客户端Socket.客户端IP:%1")).arg(clientIp), QString(tr("与客户端计算机断开连接,客户端IP:%1,port:%2,UnconnectedState:The socket is not connected.")).arg(clientIp).arg(clientPort), SystemLog::INFO);
		break;
    case QAbstractSocket::HostLookupState: 
		qDebug()  << "服务端:HostLookupState:The socket is performing a host name lookup.";
		//Global::systemLog->append(QString(tr("网络服务端状态:正在查询计算机中......客户端IP:%1")).arg(clientIp), QString(tr("正在查询客户端计算机IP:%1,port:%2,HostLookupState:The socket is performing a host name lookup.")).arg(clientIp).arg(clientPort), SystemLog::INFO);
		break;
	case QAbstractSocket::ConnectingState: 
		qDebug()  << "服务端:ConnectingState:The socket has started establishing a connection.";
		//Global::systemLog->append(QString(tr("网络服务端状态:正在创建网络连接......客户端IP:%1")).arg(clientIp), QString(tr("正在创建网络连接,客户端计算机IP:%1,port:%2,ConnectingState:The socket has started establishing a connection.")).arg(clientIp).arg(clientPort), SystemLog::INFO);
		break;
	case QAbstractSocket::ConnectedState: 
		qDebug()  << "服务端:ConnectedState:A connection is established."; 
		//Global::systemLog->append(QString(tr("网络服务端状态:TCP连接创建成功.客户端IP:%1")).arg(clientIp), QString(tr("网络已经连接成功,客户端计算机IP:%1,port:%2,ConnectedState:A connection is established.")).arg(clientIp).arg(clientPort), SystemLog::INFO);
		break;
    case QAbstractSocket::BoundState: 
		qDebug()  << "服务端:BoundState:The socket is bound to an address and port (for servers)."; 
		//Global::systemLog->append(QString(tr("网络服务端状态:服务端已绑定TCP Socket.服务端IP:%1,port:%2.")).arg(serverIp).arg(serverPort), QString(tr("网络已经连接成功,本地服务端IP:%1,port:%2,客户端计算机IP:%3,port:%4,BoundState:The socket is bound to an address and port (for servers).")).arg(serverIp).arg(serverPort).arg(clientIp).arg(clientPort), SystemLog::INFO);
		break;
    case QAbstractSocket::ClosingState: 
		qDebug()  << "服务端:ClosingState:The socket is about to close (data may still be waiting to be written)."; 
		//Global::systemLog->append(QString(tr("网络服务端状态:即将关闭一个TCP Socket.客户端IP:%1")).arg(clientIp), QString(tr("网络即将关闭,远程计算机IP:%1,port:%2,ClosingState:The socket is about to close (data may still be waiting to be written).")).arg(clientIp).arg(clientPort), SystemLog::INFO);
		break;
	case QAbstractSocket::ListeningState: 
		qDebug()  << "服务端:ListeningState:For internal use only."; 
		//Global::systemLog->append(QString(tr("网络服务端状态:Socket侦听状态.客户端IP:%1")).arg(clientIp), QString(tr("网络侦听状态,远程计算机IP:%1,port:%2")).arg(clientIp).arg(clientPort), SystemLog::INFO);
		break;
    default: 
		qDebug()<<"服务端:网络其他状态";
		//Global::systemLog->append(QString(tr("网络服务端状态:其他状态.客户端IP:%1")).arg(clientIp), QString(tr("网络其他状态,远程计算机IP:%1,port:%2")).arg(clientIp).arg(clientPort), SystemLog::INFO);
    }

	serverSocket = 0;
}
コード例 #12
0
ファイル: Server.cpp プロジェクト: anthonypdawson/wahjam
void Server::acceptNewConnection()
{
  QTcpSocket *sock = listener.nextPendingConnection();
  if (!sock) {
    return;
  }

  uint32_t addr = sock->peerAddress().toIPv4Address();
  int flag = config->acl.lookup(addr);
  if (flag == ACL_FLAG_DENY)
  {
    qDebug("Denying connection (via ACL) from %s:%u",
           sock->peerAddress().toString().toLatin1().constData(),
           sock->peerPort());
    delete sock;
    return;
  }

  group->AddConnection(sock, flag == ACL_FLAG_RESERVE);
}
コード例 #13
0
ファイル: tcplistener.cpp プロジェクト: g76r/libqtssu
void TcpListener::newConnection() {
  QTcpSocket *socket = _server->nextPendingConnection();
  if (!socket) // should never happen
    return;
  Session session = SessionManager::createSession();
  QString clientaddr = "["+socket->peerAddress().toString()
      +"]:"+QString::number(socket->peerPort());
  session.setParam("clientaddr", clientaddr);
  if (_idleHandlers.size() == 0) {
    Log::warning(session.id()) << "cannot handle connection: no idle handler"
                               << clientaddr;
    // LATER leave a reply to client
    delete socket;
  } else {
    TcpConnectionHandler *handler = _idleHandlers.takeFirst();
    socket->setParent(0);
    socket->moveToThread(handler->thread());
    handler->processConnection(socket, session);
  }
}
コード例 #14
0
ファイル: server.cpp プロジェクト: vos/qcc
void Server::incomingConnection(int socketDescriptor)
{
    QTcpSocket *socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);
    addPendingConnection(socket);

#ifdef DEBUG
    qDebug("\nServer::incomingConnection(%i): %s:%i", socketDescriptor,
           qPrintable(socket->peerAddress().toString()), socket->peerPort());
#endif

    connect(socket, SIGNAL(disconnected()), SLOT(client_disconnected()));
    connect(socket, SIGNAL(readyRead()), SLOT(client_readyRead()));

    m_clients.insert(socket, new Client);
    QccPacket(QccPacket::ConnectionAccepted).send(socket); // QccPacket::ConnectionRefused

#ifdef DEBUG
    qDebug("ConnectionAccepted");
#endif
}
コード例 #15
0
ファイル: chatserver.cpp プロジェクト: osamu-k/qt_study_osaka
void ChatServer::socketReadyRead()
{
    QTcpSocket *senderSocket = qobject_cast<QTcpSocket *>(sender());
    QString address = senderSocket->peerAddress().toString();
    quint16 port = senderSocket->peerPort();

    qDebug() << "socket ready read";
    qDebug() << "available bytes: " << senderSocket->bytesAvailable();

    while(senderSocket->bytesAvailable() > 0){
        QDataStream inStream(senderSocket);
        QString message;
        inStream >> message;
        emit messageReceived(address, port, message);
        for( auto socket: m_socketList ){
            QDataStream outStream(socket);
            outStream << message;
            socket->flush();
        }
    }
}
コード例 #16
0
ファイル: server.cpp プロジェクト: vos/qcc
void Server::client_disconnected()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (!socket) {
        qWarning("Server::client_disconnected(): Cast of sender() to QTcpSocket* failed");
        return;
    }

    Client *client = m_clients[socket];
    User *user = client->user;
    if (user)
        user->reset();

#ifdef DEBUG
    QString username = user ? user->username() : "[no user object]";
    qDebug("\nServer::client_disconnected(): '%s' (%s:%i)", qPrintable(username),
           qPrintable(socket->peerAddress().toString()), socket->peerPort());
#endif

    m_clients.remove(socket);
    delete client;
}
コード例 #17
0
ファイル: TcpServer.cpp プロジェクト: PonyYu/OCR_LIVE_HISTORY
/**
 *函数介绍:服务端socket出错
 *输入参数:无
 *返回值:  无
 */
void TcpServer::serverSocketError(QAbstractSocket::SocketError socketError)
{
	QTcpSocket *serverSocket = qobject_cast<QTcpSocket *>(sender());
	QString clientIp = serverSocket->peerAddress().toString();
	int clientPort = serverSocket->peerPort();
	QString serverIp = this->serverAddress().toString();
	int serverPort = this->serverPort();

    emit serverSocketErrorSignal(socketError);
	switch (socketError)
    {
    case QAbstractSocket::ConnectionRefusedError:  
		//Global::systemLog->append(QString(tr("网络服务端出错:拒绝连接.")).arg(clientIp), QString(tr("客户端计算机IP:%1,port:%2拒绝连接,The connection was refused by the peer (or timed out).")).arg(clientIp).arg(clientPort), SystemLog::ERROR);
		break;
    case QAbstractSocket::RemoteHostClosedError:   
		//Global::systemLog->append(QString(tr("网络服务端出错:远程主机关闭了连接.")).arg(clientIp), QString(tr("客户端计算机IP:%1,port:%2关闭了SOCKET连接,服务端SOCKET也即将关闭,The remote host closed the connection. ")).arg(clientIp).arg(clientPort), SystemLog::ERROR);
		break;
    case QAbstractSocket::HostNotFoundError:   
		//Global::systemLog->append(QString(tr("网络服务端出错:找不到远程主机.")).arg(clientIp), QString(tr("找不到客户端计算机IP:%1,port:%2,The host address was not found. ")).arg(clientIp).arg(clientPort), SystemLog::ERROR);
		break;
	case QAbstractSocket::SocketResourceError:  
		//Global::systemLog->append(QString(tr("网络服务端出错:Socket资源不够.")).arg(clientIp), QString(tr("本地Socket资源不够,客户端计算机IP:%1,port:%2,The local system ran out of resources (e.g., too many sockets). ")).arg(clientIp).arg(clientPort), SystemLog::ERROR);
		break;
    case QAbstractSocket::SocketTimeoutError:  
		//Global::systemLog->append(QString(tr("网络服务端出错:操作超时.")).arg(clientIp), QString(tr("服务端网络操作超时,客户端计算机IP:%1,port:%2,The socket operation timed out. ")).arg(clientIp).arg(clientPort), SystemLog::ERROR);
		break;
	case QAbstractSocket::DatagramTooLargeError:  
		//Global::systemLog->append(QString(tr("网络服务端出错:数据包过大.")).arg(clientIp), QString(tr("服务端网络数据包过大,客户端计算机IP:%1,port:%2,The socket operation timed out. ")).arg(clientIp).arg(clientPort), SystemLog::ERROR);
		break;
	case QAbstractSocket::NetworkError:  
		//Global::systemLog->append(QString(tr("网络服务端出错:计算机网络出错.")).arg(clientIp), QString(tr("网络出错,可能网线断开了,客户端计算机IP:%1,port:%2,The datagram was larger than the operating system's limit (which can be as low as 8192 bytes).")).arg(clientIp).arg(clientPort), SystemLog::ERROR);
		break;
    default:
		int i = 0;
		//Global::systemLog->append(QString(tr("网络服务端出错:未知错误,SocketError:%2")).arg(clientIp).arg(socketError), QString(tr("未知错误,客户端计算机IP:%1,port:%2")).arg(clientIp).arg(clientPort), SystemLog::ERROR);

    }
    qDebug() << "服务端socket出错";
}
コード例 #18
0
void ClientControllerWidget::updateGuiState()
{
  QTcpSocket *socket = _client->getServerConnection().getSocket();
  switch (socket->state()) {
    case QAbstractSocket::ConnectedState:
      _ui.connectionStatus->setText(tr("Connected to %1 on port %2").arg(socket->peerAddress().toString()).arg(socket->peerPort()));
      _ui.savePath->setEnabled(false);
      _ui.savePathButton->setEnabled(false);
      break;
    case QAbstractSocket::UnconnectedState:
      _ui.connectionStatus->setText(tr("No connection."));
      _ui.savePath->setEnabled(true);
      _ui.savePathButton->setEnabled(true);
      break;
  }
}
コード例 #19
0
/*!
    \internal
 */
void QWebSocketServerPrivate::handshakeReceived()
{
    if (Q_UNLIKELY(!currentSender)) {
        return;
    }
    QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender);
    if (Q_UNLIKELY(!pTcpSocket)) {
        return;
    }
    //When using Google Chrome the handshake in received in two parts.
    //Therefore, the readyRead signal is emitted twice.
    //This is a guard against the BEAST attack.
    //See: https://www.imperialviolet.org/2012/01/15/beastfollowup.html
    //For Safari, the handshake is delivered at once
    //FIXME: For FireFox, the readyRead signal is never emitted
    //This is a bug in FireFox (see https://bugzilla.mozilla.org/show_bug.cgi?id=594502)
    if (!pTcpSocket->canReadLine()) {
        return;
    }
    disconnect(pTcpSocket, &QTcpSocket::readyRead,
               this, &QWebSocketServerPrivate::handshakeReceived);
    Q_Q(QWebSocketServer);
    bool success = false;
    bool isSecure = false;

    if (m_pendingConnections.length() >= maxPendingConnections()) {
        pTcpSocket->close();
        pTcpSocket->deleteLater();
        setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
                 QWebSocketServer::tr("Too many pending connections."));
        return;
    }

    QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure);
    QTextStream textStream(pTcpSocket);
    request.readHandshake(textStream, MAX_HEADERLINE_LENGTH, MAX_HEADERLINES);

    if (request.isValid()) {
        QWebSocketCorsAuthenticator corsAuthenticator(request.origin());
        Q_EMIT q->originAuthenticationRequired(&corsAuthenticator);

        QWebSocketHandshakeResponse response(request,
                                             m_serverName,
                                             corsAuthenticator.allowed(),
                                             supportedVersions(),
                                             supportedProtocols(),
                                             supportedExtensions());

        if (response.isValid()) {
            QTextStream httpStream(pTcpSocket);
            httpStream << response;
            httpStream.flush();

            if (response.canUpgrade()) {
                QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket,
                                                                        request,
                                                                        response);
                if (pWebSocket) {
                    addPendingConnection(pWebSocket);
                    Q_EMIT q->newConnection();
                    success = true;
                } else {
                    setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
                             QWebSocketServer::tr("Upgrade to WebSocket failed."));
                }
            }
            else {
                setError(response.error(), response.errorString());
            }
        } else {
            setError(QWebSocketProtocol::CloseCodeProtocolError,
                     QWebSocketServer::tr("Invalid response received."));
        }
    }
    if (!success) {
        pTcpSocket->close();
    }
}
コード例 #20
0
ファイル: httpServer.cpp プロジェクト: Darknautilus/tp-vod
void httpServer::getClientRequest()
{
	QTcpSocket *client = qobject_cast<QTcpSocket *>(sender());	
	if(client->canReadLine())
	{
		QStringList lines = QString(client->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
		if(lines[0] == "GET")
		{
			viewMessage(QString::fromUtf8("Envoi du catalogue à ")+client->peerAddress().toString()+":"+QString::number(client->peerPort()));
			QFile catalogue(QCoreApplication::applicationDirPath()+"/catalog.tmp");
			catalogue.open(QIODevice::ReadOnly | QIODevice::Text);
			QTextStream os(client);
			QTextStream is(&catalogue);
			os << "HTTP/1.1 200 OK\r\nServer: TP_Serveur_3208\r\nConnection: Keep-Alive\r\nContent-Type: text/txt\r\nContent-Length: " << catalogue.size() << "\r\n\r\n";
			QString line = is.readLine();
			while(!line.isNull())
			{
				os << line.toLocal8Bit().constData() << "\r\n";
				line = is.readLine();
			}
			catalogue.close();
		}
	}	
}
コード例 #21
0
void ControlToMasterConnectionHandler::Private::onSocketStateChanged(QAbstractSocket::SocketState state)
{
  QTcpSocket *socket = _conn->socket();
  switch (state) {
    case QAbstractSocket::ConnectedState:
      HL_INFO(HL, QString("Connected to master server (address=%1; port=%2)").arg(socket->peerAddress().toString()).arg(socket->peerPort()).toStdString());
      break;
    case QAbstractSocket::UnconnectedState:
      if (!_shutdown) {
        HL_ERROR(HL, QString("Lost connection to master server (error=%1)").arg(socket->errorString()).toStdString());
        _owner->startup(_opts);
      }
      emit _owner->disconnected();
      break;
  }
}
コード例 #22
0
ファイル: serveur.cpp プロジェクト: Ooya/tp3
void serveur::newClient()
{
    QTcpSocket *clientConnection = server->nextPendingConnection();
    clients.push_back(clientConnection);
    qDebug()<<"Serveur : nouvelle conexion : "<<clientConnection->peerPort();
}
コード例 #23
0
void MainWindow::newClient()
{
    if(connectedMode=="Tcp socket (QTcpServer)")
    {
        QTcpSocket *newClient = TcpServer.nextPendingConnection();
        ui->statusBarApp->showMessage("New client connected: "+newClient->peerAddress().toString(),10000);
        //connect(newClient, SIGNAL(readyRead()), this, SLOT(dataincommingUI()));
        connect(newClient, SIGNAL(disconnected()), this, SLOT(clientLeave()));
        connect(newClient, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(newErrorTcp(QAbstractSocket::SocketError)));
        connect(newClient, SIGNAL(readyRead()), this, SLOT(newData()));
        tcpSocket << new tcpClientInfo;
        tcpSocket.last()->tcpSocket=newClient;
        tcpSocket.last()->isConnected=true;
        tcpSocket.last()->LastEditionMode=ui->comboBoxTypeTx->currentText();
        QListWidgetItem *TempItem=new QListWidgetItem(QIcon(":/images/preferences-desktop-user.png"),QString::number(idConnection++)+": "+newClient->peerAddress().toString());
        TempItem->setToolTip("ip: "+newClient->peerAddress().toString()+", port: "+QString::number(newClient->peerPort()));
        tcpSocket.last()->ItemInList=TempItem;
        ui->listWidgetClient->addItem(TempItem);

        //compression part
        tcpSocket.last()->compression=NULL;
        switch(ui->compressionType->currentIndex())
        {
        case 2:
            tcpSocket.last()->compression=new ZlibCompressionTcpSocket(ui->compressionBufferSize->value(),9,ui->compressionByPacket->isChecked());
            break;
        case 3:
            tcpSocket.last()->compression=new GzipCompressionTcpSocket(ui->compressionBufferSize->value(),9,ui->compressionByPacket->isChecked());
            break;
        case 0:
            tcpSocket.last()->compression=new Lz4HcCompressionTcpSocket();
            break;
        case 1:
        default:
            tcpSocket.last()->compression=new Lz4CompressionTcpSocket();
            break;
        }
    }
    if(connectedMode==COMBOBOXTEXTLOCALSOCK)
    {
        QLocalSocket *newClient = LocalServer.nextPendingConnection();
        ui->statusBarApp->showMessage("New client connected",10000);
        connect(newClient, SIGNAL(disconnected()), this, SLOT(clientLeave()));
        connect(newClient, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(newErrorLocal(QLocalSocket::LocalSocketError)));
        connect(newClient, SIGNAL(readyRead()), this, SLOT(newData()));
        localSocket << new localClientInfo;
        localSocket.last()->localSocket=newClient;
        localSocket.last()->isConnected=true;
        localSocket.last()->LastEditionMode=ui->comboBoxTypeTx->currentText();
        localSocket.last()->ItemInList=new QListWidgetItem(QIcon(":/images/preferences-desktop-user.png"),QString::number(idConnection++)+": Local Client");
        ui->listWidgetClient->addItem(localSocket.last()->ItemInList);

        //compression part
        localSocket.last()->compression=NULL;
        switch(ui->compressionType->currentIndex())
        {
        case 2:
            localSocket.last()->compression=new ZlibCompressionTcpSocket(ui->compressionBufferSize->value(),9,ui->compressionByPacket->isChecked());
            break;
        case 3:
            localSocket.last()->compression=new GzipCompressionTcpSocket(ui->compressionBufferSize->value(),9,ui->compressionByPacket->isChecked());
            break;
        case 0:
            localSocket.last()->compression=new Lz4HcCompressionTcpSocket();
            break;
        case 1:
        default:
            localSocket.last()->compression=new Lz4CompressionTcpSocket();
            break;
        }
    }
    if(ui->listWidgetClient->count()==1)
    {
        ui->listWidgetClient->item(0)->setSelected(true);
        updateCurrentData();
    }
}
コード例 #24
0
ファイル: server.cpp プロジェクト: vos/qcc
void Server::client_readyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (!socket) {
        qWarning("Server::client_readyRead(): Cast of sender() to QTcpSocket* failed");
        return;
    }

#ifdef DEBUG
    qDebug("\nServer::client_readyRead(): %li bytes available", (long)socket->bytesAvailable());
#endif

    Client *client = m_clients[socket];
    QDataStream in(socket);
    in.setVersion(QDataStream::Qt_4_0);
    if (client->packetSize == 0) {
        if (socket->bytesAvailable() < (int)sizeof(quint32)) // packet size
            return;
        in >> client->packetSize;
    }
    if (socket->bytesAvailable() < client->packetSize)
        return;
    client->packetSize = 0; // reset packet size

    qint32 type;
    in >> type;

#ifdef DEBUG
    qDebug("PacketType %i (%s) from '%s' (%s:%i)", type,
           qPrintable(QccPacket::typeString((QccPacket::PacketType)type)),
           qPrintable(client->user ? client->user->username() : "[no user object]"),
           qPrintable(socket->peerAddress().toString()), socket->peerPort());
#endif

    switch ((QccPacket::PacketType)type) {
    case QccPacket::UserRegister:
    {
        QString username, password;
        QByteArray publicKey;
        in >> username >> password >> publicKey;
#ifdef DEBUG
        qDebug("Username = '******' password = '******'", qPrintable(username), qPrintable(password));
#endif
        if (username.isEmpty()) {
            QString reason = "The username cannot be empty.";
            QccPacket packet(QccPacket::RegisterFailure);
            packet.stream() << reason;
            packet.send(socket);
#ifdef DEBUG
            qDebug("RegisterFailure: %s", qPrintable(reason));
#endif
            break;
        }
        if (m_users.contains(username)) {
            QString reason = QString("The username \"%1\" is not available.").arg(username);
            QccPacket packet(QccPacket::RegisterFailure);
            packet.stream() << reason;
            packet.send(socket);
#ifdef DEBUG
            qDebug("RegisterFailure: %s", qPrintable(reason));
#endif
            break;
        }
#ifdef DEBUG
            qDebug("RegisterSuccess");
#endif
        User *user = new User(username, password);
        user->setPublicKey(publicKey);
        user->setSocket(socket);
        connect(user, SIGNAL(statusChanged()), SLOT(client_statusChanged()));
        user->setStatus(User::Online);
        m_users.insert(username, user);
        saveUsers();
        client->user = user;
        QccPacket(QccPacket::RegisterSuccess).send(socket);
        break;
    }
    case QccPacket::UserAuthentication:
    {
        QString username, password;
        QByteArray publicKey;
        in >> username >> password >> publicKey;
#ifdef DEBUG
        qDebug("Username = '******' password = '******'", qPrintable(username), qPrintable(password));
#endif
        User *user = m_users.contains(username) ? m_users[username] : NULL;
        if (user && user->matchPassword(password)) {
#ifdef DEBUG
            qDebug("AuthenticationSuccess");
#endif
            user->setPublicKey(publicKey);
            user->setSocket(socket);
            user->setStatus(User::Online);
            client->user = user;
            QccPacket(QccPacket::AuthenticationSuccess).send(socket);
        } else {
            QString reason = "The username or password you entered is incorrect.";
            QccPacket packet(QccPacket::AuthenticationFailure);
            packet.stream() << reason;
            packet.send(socket);
#ifdef DEBUG
            qDebug("AuthenticationFailure: %s", qPrintable(reason));
#endif
        }
        break;
    }
    case QccPacket::RequestAuthorization:
    {
        QString username;
        in >> username;
        if (!m_users.contains(username)) {
            QString reason = QString("The user \"%1\" does not exist.").arg(username);
            QccPacket packet(QccPacket::AuthorizationFailure);
            packet.stream() << reason;
            packet.send(socket);
#ifdef DEBUG
            qDebug("AuthorizationFailure: %s", qPrintable(reason));
#endif
            break;
        }
        if (client->user->username() == username) {
            QString reason = QString("You cannot add yourself.");
            QccPacket packet(QccPacket::AuthorizationFailure);
            packet.stream() << reason;
            packet.send(socket);
#ifdef DEBUG
            qDebug("AuthorizationFailure: %s", qPrintable(reason));
#endif
            break;
        }
        if (client->user->containsContact(username)) {
            QString reason = QString("The user \"%1\" is already on your contact list.").arg(username);
            QccPacket packet(QccPacket::AuthorizationFailure);
            packet.stream() << reason;
            packet.send(socket);
#ifdef DEBUG
            qDebug("AuthorizationFailure: %s", qPrintable(reason));
#endif
            break;
        }
        User *receiver = m_users.value(username);
        if (receiver && receiver->isOnline()) {
            QccPacket packet(QccPacket::RequestAuthorization);
            packet.stream() << client->user->username();
            packet.send(receiver->socket());
#ifdef DEBUG
            qDebug("RequestAuthorization: forwarded to '%s'", qPrintable(username));
#endif
        } else {
            QString reason = QString("The user \"%1\" is not online.").arg(username);
            QccPacket packet(QccPacket::AuthorizationFailure);
            packet.stream() << reason;
            packet.send(socket);
#ifdef DEBUG
            qDebug("AuthorizationFailure: %s", qPrintable(reason));
#endif
        }
        break;
    }
    case QccPacket::AuthorizationAccepted:
    {
        QString username;
        in >> username;
        if (username.isEmpty())
            break;
        User *receiver = m_users[username];
        if (receiver && receiver->isOnline()) {
            receiver->addContact(client->user->username());
            client->user->addContact(username);
            saveUsers();
            QccPacket packet(QccPacket::AuthorizationAccepted);
            packet.stream() << client->user->username() << (qint32)client->user->status() << client->user->publicKey();
            packet.send(receiver->socket());
            QccPacket packet2(QccPacket::AuthorizationAccepted);
            packet2.stream() << username << (qint32)receiver->status() << receiver->publicKey();
            packet2.send(socket);
        }
#ifdef DEBUG
            qDebug("AuthorizationAccepted: forwarded to '%s'", qPrintable(username));
#endif
        break;
    }
    case QccPacket::AuthorizationDeclined:
    {
        QString username;
        in >> username;
        if (username.isEmpty())
            break;
        User *receiver = m_users.value(username);
        if (receiver && receiver->isOnline()) {
            QccPacket packet(QccPacket::AuthorizationDeclined);
            packet.stream() << client->user->username();
            packet.send(receiver->socket());
        }
#ifdef DEBUG
            qDebug("AuthorizationDeclined: forwarded to '%s'", qPrintable(username));
#endif
        break;
    }
    case QccPacket::RequestContactList:
    {
        QccPacket packet(QccPacket::ContactList);
        QSet<QString> contacts = client->user->contacts();
        packet.stream() << (qint32)contacts.count();
        foreach (const QString &contactName, contacts) {
            User *contact = m_users.value(contactName);
            if (!contact) continue;
            packet.stream() << contactName << qint32(contact->status()) << contact->publicKey();
        }
        packet.send(socket);
#ifdef DEBUG
            qDebug("ContactList: %i contacts send", contacts.count());
#endif
        break;
    }
    case QccPacket::RemoveContact:
    {
        QString username;
        in >> username;
        if (client->user->removeContact(username)) {
            QccPacket packet(QccPacket::ContactRemoved);
            packet.stream() << username;
            packet.send(socket);
            User *receiver = m_users[username];
            if (receiver && receiver->removeContact(client->user->username()) && receiver->isOnline()) {
                QccPacket packet2(QccPacket::ContactRemoved);
                packet2.stream() << client->user->username();
                packet2.send(receiver->socket());
            }
            saveUsers();
#ifdef DEBUG
            qDebug("ContactRemoved: contact '%s' removed", qPrintable(username));
#endif
        }
        break;
    }
    case QccPacket::Message:
    {
        qint32 id;
        QString receiverName;
        QString message;
        in >> id >> receiverName >> message;
        if (!client->user->containsContact(receiverName)) {
            QString reason = QString("The user \"%1\" is not on your contact list.").arg(receiverName);
            QccPacket packet(QccPacket::MessageFailure);
            packet.stream() << reason;
            packet.send(socket);
#ifdef DEBUG
            qDebug("MessageFailure: %s", qPrintable(reason));
#endif
            break;
        }
        User *receiver = m_users.value(receiverName);
        if (receiver && receiver->isOnline()) {
            QccPacket packet(QccPacket::Message);
            packet.stream() << id << client->user->username() << message;
            packet.send(receiver->socket());
#ifdef DEBUG
            qDebug("Message: forwarded to '%s'", qPrintable(receiverName));
#endif
        } else {
            QString reason = QString("The user \"%1\" is not online.").arg(receiverName);
            QccPacket packet(QccPacket::MessageFailure);
            packet.stream() << id << receiverName << reason;
            packet.send(socket);
#ifdef DEBUG
            qDebug("MessageFailure: failed to forward to '%s' => %s",
                   qPrintable(receiverName), qPrintable(reason));
#endif
        }
        break;
    }
    case QccPacket::MessageSuccess:
    {
        qint32 id;
        QString receiverName;
        in >> id >> receiverName;
        User *receiver = m_users.value(receiverName);
        if (receiver && receiver->isOnline()) {
            QccPacket packet(QccPacket::MessageSuccess);
            packet.stream() << id << client->user->username();
            packet.send(receiver->socket());
#ifdef DEBUG
            qDebug("MessageSuccess: forwarded to '%s'", qPrintable(receiverName));
#endif
        }
        break;
    }
    default:
        qWarning("Server::client_readyRead(): Illegal PacketType %i", type);
        return;
    }
コード例 #25
0
void MonitorServer::slotDisconnected(int descriptor)
{
    for(int i=0;i<MonitorList.count();i++)
    {
        QTcpSocket *item = MonitorList.at(i);
        if(item->socketDescriptor()==descriptor)
        {
             QString strLog = QString("%1(%2) disconnect MonitorServer.").arg(item->peerAddress().toString()).arg(item->peerPort());
             LogFile(glbfileLog,strLog);
            MonitorList.removeAt(i);
            return;
        }
    }
    return;
}
コード例 #26
0
ファイル: mrimconnection.cpp プロジェクト: reindeer/qutim
void MrimConnection::disconnected()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    Q_ASSERT(socket);

    debug()<<"Disconnected from server"<<qPrintable( Utils::toHostPortPair(socket->peerAddress(),socket->peerPort()) );

    if (socket == p->SrvReqSocket())
    {
        if (!p->imHost.isEmpty() && p->imPort > 0)
        {//all is fine, connecting to IM server
            p->IMSocket()->connectToHost(p->imHost,p->imPort);
        }
        else
        {
            critical()<<"Oh god! This is epic fail! We didn't recieve any server, so connection couldn't be established!";
        }
    } else emit loggedOut();
}
コード例 #27
0
ファイル: tcpsrc.cpp プロジェクト: hecko/rtl-sdrangelove
void TCPSrc::onNewConnection()
{
	while(m_tcpServer->hasPendingConnections()) {
		QTcpSocket* connection = m_tcpServer->nextPendingConnection();
		connect(connection, SIGNAL(disconnected()), this, SLOT(onDisconnected()));

		switch(m_sampleFormat) {

			case FormatNFM:
			case FormatSSB: {
				quint32 id = (FormatSSB << 24) | m_nextSSBId;
				MsgTCPSrcConnection* msg = MsgTCPSrcConnection::create(true, id, connection->peerAddress(), connection->peerPort());
				m_nextSSBId = (m_nextSSBId + 1) & 0xffffff;
				m_ssbSockets.push_back(Socket(id, connection));
				msg->submit(m_uiMessageQueue, (PluginGUI*)m_tcpSrcGUI);
				break;
			}

			case FormatS16LE: {
				quint32 id = (FormatS16LE << 24) | m_nextS16leId;
				MsgTCPSrcConnection* msg = MsgTCPSrcConnection::create(true, id, connection->peerAddress(), connection->peerPort());
				m_nextS16leId = (m_nextS16leId + 1) & 0xffffff;
				m_s16leSockets.push_back(Socket(id, connection));
				msg->submit(m_uiMessageQueue, (PluginGUI*)m_tcpSrcGUI);
				break;
			}

			default:
				delete connection;
				break;
		}
	}
}
コード例 #28
0
ファイル: zhttpserver.cpp プロジェクト: zccrs/z-http-service
bool ZHttpServer::startServer(quint16 port)
{
    if(m_tcpServer->isListening())
        return true;

    if(!m_tcpServer->listen(QHostAddress::Any, port)){
        qWarning() << "HttpServer: error: " << m_tcpServer->errorString();
        return false;
    }else{
        qWarning() << "HttpServer: OK";
    }
    connect(m_tcpServer, &QTcpServer::newConnection, [this]{
        QTcpSocket *socket = m_tcpServer->nextPendingConnection();
        qWarning() << "HttpServer: new connect:" << socket->peerAddress().toString() << socket->peerName() << socket->peerPort();

        connect(socket, &QTcpSocket::readyRead, [socket, this]{
            HttpInfo info(socket->readAll());

            qWarning() << info.url();

            const QByteArray &query = info.url().query().toUtf8();
            QMap<QByteArray, QByteArray> command_map;

            QFileInfo fileInfo(sysroot + info.url().path());

            if (fileInfo.isFile() && fileInfo.isExecutable()) {
                execProcess((fileInfo.fileName() + " " + info.url().query(QUrl::FullyDecoded)).toLatin1(), socket);

                return;
            }

            if(!query.isEmpty()) {
                QByteArrayList commands = query.split('&');

                qWarning() << "HttpServer: command:" << commands;

                for(const QByteArray &comm : commands) {
                    if(comm.isEmpty())
                        continue;

                    const QByteArrayList &tmp_list = comm.split('=');

                    if(tmp_list.count() != 2 || tmp_list.first().isEmpty()) {
                        socket->write(messagePackage("", "text/Html", HttpInfo::BadRequest, QString("Grammatical errors: \"%1\"").arg(QString(comm))));
                        socket->close();
                        return;
                    }

                    command_map[tmp_list.first()] = tmp_list.last();
                }
            }

            if(command_map.value(ACTION) == ACTION_EXEC) {
                execProcess(QUrl::fromPercentEncoding(command_map.value(COMMAND)), socket);
            } else {
                QPointer<QTcpSocket> socket_pointer = socket;

                readFile(info.url(), socket);

                if (socket_pointer)
                    socket->close();
            }
        });
        connect(socket, &QTcpSocket::disconnected, [socket]{
            qWarning() << "HttpServer: disconnected: " << socket->peerAddress().toString() << socket->peerName() << socket->peerPort();
            socket->deleteLater();
        });
    });

    return true;
}
コード例 #29
0
ファイル: tcpgatedialog.cpp プロジェクト: wtpluscn/wttools
void TcpGateDialog::onConnected()
{
	QTcpSocket* tcpSocket = (QTcpSocket*)sender();
	
	Log2Main(tr("connected to %1:%2 succeed").arg(tcpSocket->peerAddress().toString()).arg(tcpSocket->peerPort()));
	
	m_ndConnect.btnStart->setText(tr("Break"));
	m_ndConnect.bConnected = true;
	m_ndConnect.spinPort->setEnabled(false);
	m_ndConnect.cbIp->setEnabled(false);	
}
コード例 #30
-1
ファイル: server.cpp プロジェクト: eiger824/TCP_Messenger
  void Server::acceptUser() {
    //to be called every time a new connection is received
    QTcpSocket *socket = m_tcp_server->nextPendingConnection();
    debugInfo("New incoming connection, from IP " +
	      socket->peerAddress().toString() +
	      " and port: " + QString::number(socket->peerPort()));
    //check if ip is registered
    if (!isThisIpRegistered(socket->peerAddress().toString())) {
      //then parse user
      UE new_ue;
      new_ue.name = "";
      new_ue.ip = socket->peerAddress().toString();
      //will change when ue_name() is sent
      new_ue.rx_port = 0;
      m_online_users.append(new_ue);
      debugInfo("New empty UE registered!");
    } else {
      debugInfo("user is transmitting either its name or data");
      socket->waitForReadyRead(1000);
      //parse data
      QDataStream in(socket);
      in.setVersion(QDataStream::Qt_4_0);
      debugInfo("m_block_size: " + QString::number(m_block_size));
      if (m_block_size == 0) {
	if (socket->bytesAvailable() < (int)sizeof(quint16))
	  return;
      
	in >> m_block_size;
      }
      debugInfo("bytes available in socket: " + QString::number(socket->bytesAvailable()));
    
      if (socket->bytesAvailable() < m_block_size)
	return;
    
      QString message;
      in >> message;
    
      debugInfo(">Message: [" + message + "]");

      ProtocolStreamType_UE type;
      QStringList params = m_protocol->parseStream_UE(type, message);

      switch (type) {
      case UE_REGISTER:
	{
	  QString temp_name = params.at(0);
	  quint16 temp_port = (quint16) params.at(1).toInt();
	  DLOG (INFO) << "Parsed port: " << temp_port;
	  if (temp_name.isEmpty()) {
	    m_block_size=0;
	    return;
	  }
	  UE temp;
	  int index;
	  if (!isThisNameRegistered(temp_name)) {
	    //case for same ip, different name
	    debugInfo("New user " + temp_name + " connected from same IP. Registering user.");
	    temp.name = temp_name;
	    temp.ip = socket->peerAddress().toString();
	    //parse ue_rx_port
	    temp.rx_port = temp_port;
	    index = getIndexOfUEIp(socket->peerAddress().toString());
	    if (m_online_users.at(index).name.isEmpty()) {
	      //first time, when username is still empty
	      if (index != -1) {
		temp = m_online_users.at(index);
		temp.name = temp_name;
		temp.rx_port = temp_port;
		m_online_users.replace(index,temp);
	      }
	    } else {
	      //same ip but different username, then append new UE
	      m_online_users.append(temp);
	    }
	  } else {
	    LOG (ERROR) << "User already exists on server. Notifying user...";
	    //inform user of currently online users
	    QByteArray block;
	    QDataStream out(&block, QIODevice::WriteOnly);
	    out.setVersion(QDataStream::Qt_4_0);
	    out << (quint16)0;
	    out << QString("ue_error(Existing user on server. Choose other username);");
	    out.device()->seek(0);
	    out << (quint16)(block.size() - sizeof(quint16));
	    DLOG (INFO) <<"Sending error message to UE ...\n";
	    m_log_label->setText(m_log_label->toPlainText()
			      + "\nError: attempted connection with same "
			      "username from same IP. Sending error to client...");
	    socket->write(block);
	    //reset m_block_size
	    m_block_size = 0;
	    return;
	  }
	  DLOG (INFO) << "New user is online: " << temp;
	  debugInfo("Nr. online users: " + QString::number(m_online_users.size()));
	  if (m_log_label->toPlainText() != "") {
	    m_log_label->setText(m_log_label->toPlainText() + "\n[" + temp.name + "]@" +
			      temp.ip + ":" +
			      QString::number(temp.rx_port) + " is now online.");
	  } else {
	    m_log_label->setText(m_log_label->toPlainText() + "[" + temp.name + "]@" +
			      temp.ip + ":" +
			      QString::number(temp.rx_port) + " is now online.");
	  }
	  //parse online users
	  QString users;
	  for (auto user: m_online_users) {
	    users += user.name + "\n";
	  }
	  users.chop(1);
	  m_online_users_label->setText(users);
	  qobject_cast<QLabel*>(m_main_layout->itemAt(2)->widget())->setText("Currently online users("
									  + QString::number(m_online_users.size()) + "):");
	  //inform user of currently online users
	  QByteArray block;
	  QDataStream out(&block, QIODevice::WriteOnly);
	  out.setVersion(QDataStream::Qt_4_0);
	  out << (quint16)0;
	  QStringList params;
	  for (auto user: m_online_users) {
	    params << user.name;
	  }
	  out << m_protocol->constructStream_Server(params,
						    ProtocolStreamType_Server::SERVER_ALL);
	  out.device()->seek(0);
	  out << (quint16)(block.size() - sizeof(quint16));
	  DLOG (INFO) <<"Sending information about currently online users...\n";
	  /*At this point, this block will be sent to all current users, not only to the
	    user that is currently connected*/
	  for (auto connection: m_online_users) {
	    QTcpSocket *temp_socket = new QTcpSocket(this);
	    temp_socket->connectToHost(QHostAddress(connection.ip), connection.rx_port);
	    if (!temp_socket->waitForConnected(3000)) {
	      LOG (ERROR) << "ERROR: Connection attempt @"
			  << connection.ip.toStdString() << ":"
			  << connection.rx_port << " timed out. Omitting current...";
	    } else {
	      debugInfo("Connection to client @" + connection.ip + ":"
			+ QString::number(connection.rx_port) + " was established. Now sending...");
	      temp_socket->write(block);
	      if (!temp_socket->waitForBytesWritten()) {
		LOG (ERROR) << "ERROR: Connection attempt @"
			    << connection.ip.toStdString() << ":"
			    << connection.rx_port << " timed out. Omitting current...";
	      } else {
		debugInfo("Transmission to client @" + connection.ip + ":"
			  + QString::number(connection.rx_port) + " was successful!");
	      }
	    }
	    temp_socket->disconnectFromHost();
	    if (temp_socket->state() == QAbstractSocket::UnconnectedState ||
		temp_socket->waitForDisconnected(1000)) {
	      debugInfo("Socket disconnected.");
	    }
	  }

	  break;

	  
	}
      case UE_ACK:
	{
	  m_log_label->setText(m_log_label->toPlainText() + "\n" + message);
	  debugInfo("Going to forward user ack to destination");
	  QByteArray block;
	  QDataStream out(&block, QIODevice::WriteOnly);
	  out.setVersion(QDataStream::Qt_4_0);
	  out << (quint16)0;
	  out << m_protocol->constructStream_Server(QStringList(message),
						    ProtocolStreamType_Server::SERVER_FWD_TO_SENDER);
	  out.device()->seek(0);
	  out << (quint16)(block.size() - sizeof(quint16));

	  //and lookup destination details for given user
	  QString dest = params.at(0);
	  QString from = params.at(1);
	  unsigned int message_id = (unsigned int) params.at(2).toInt();

	  //Create temporary socket
	  QTcpSocket* dest_socket = new QTcpSocket(this);
	  QString dest_ip;
	  quint16 dest_port;
	  int index = getIndexOfUEName(dest);
	  if (index != -1) {
	    dest_ip = m_online_users.at(index).ip;
	    dest_port = m_online_users.at(index).rx_port;
	    debugInfo("Going to forward ack to " + dest_ip + ":" + QString::number(dest_port));
	  } else {
	    LOG (ERROR) << "ERROR: name was not found on server. Returning...";
	    m_block_size=0;
	    return;
	  }
	  dest_socket->connectToHost(QHostAddress(dest_ip), dest_port);

	  if (!dest_socket->waitForConnected(2000)) {
	    debugInfo("ERROR: request timed out");
	  } else {
	    debugInfo("Established connection with client. Forwarding user ack...");
	    dest_socket->write(block);
	    if (!dest_socket->waitForBytesWritten(5000)) {
	      debugInfo("ERROR: transmission timed out");
	    } else {
	      debugInfo("Success! ACK was forwarded to destination");
	    }
	    dest_socket->disconnectFromHost();
	  }
	  break;
	}
      case UE_ERROR:
	{
	  debugInfo("Some error encountered by user. Returning ...");
	  m_block_size=0;
	  return;
	}
      case UE_MESSAGE:
	{
	  m_log_label->setText(m_log_label->toPlainText() + "\n" + message);
	  //and send it back to the user
	  debugInfo("Going to resend message to dest client: [" + message + "]");
	  
	  QString content = params.at(0);
	  QString dest = params.at(1);
	  QString from = params.at(2);
	  unsigned int message_id = (unsigned int) params.at(3).toInt();
	  
	  DLOG (INFO) << "Message: " << content.toStdString() << ", from " << from.toStdString()
		      << " and to " << dest.toStdString()
		      << ", with message ID: " << message_id;
	  QByteArray block;
	  QDataStream out(&block, QIODevice::WriteOnly);
	  out.setVersion(QDataStream::Qt_4_0);
	  out << (quint16)0;
	  out << m_protocol->constructStream_Server(QStringList(message),
						    ProtocolStreamType_Server::SERVER_FWD_TO_SENDER);
	  out.device()->seek(0);
	  out << (quint16)(block.size() - sizeof(quint16));
	  if (dest == from) {
	    debugInfo("WARNING: Message intended for self UE. Sending back to user...");
	    socket->write(block);
	    if (!socket->waitForBytesWritten(2000)) {
	      LOG (ERROR) << "ERROR: transmission timeout";
	    } else {
	      debugInfo("Success!");
	    }
	  } else {
	    QTcpSocket *dest_socket = new QTcpSocket(this);
	    QString dest_ip;
	    quint16 dest_port;
	    int index = getIndexOfUEName(dest);
	    if (index != -1) {
	      dest_ip = m_online_users.at(index).ip;
	      dest_port = m_online_users.at(index).rx_port;
	      debugInfo("Going to forward message to " + dest_ip + ":" + QString::number(dest_port));
	    } else {
	      LOG (ERROR) << "ERROR: name was not found on server. Returning...";
	      m_block_size=0;
	      return;
	    }
	    dest_socket->connectToHost(QHostAddress(dest_ip), dest_port);
	    if (!dest_socket->waitForConnected(2000)) {
	      debugInfo("ERROR: request timed out");
	    } else {
	      debugInfo("Established connection with client. Sending...");
	      dest_socket->write(block);
	      if (!dest_socket->waitForBytesWritten(5000)) {
		debugInfo("ERROR: transmission timed out");
	      } else {
		debugInfo("Success! Message was forwarded to destination");
	      }
	      dest_socket->disconnectFromHost();
	      //and send an ack to the user to inform that message was received
	      QByteArray ack_data;
	      QDataStream ack(&ack_data, QIODevice::WriteOnly);
	      ack.setVersion(QDataStream::Qt_4_0);
	      ack << (quint16)0;
	      QStringList params;
	      params << from << QString::number(message_id);
	      ack << m_protocol->constructStream_Server(params,
							ProtocolStreamType_Server::SERVER_ACK);
	      ack.device()->seek(0);
	      debugInfo("Sending ack to user: "******"ERROR: transmission timeout!";
	      } else {
		debugInfo("Success!");
	      }
	    }
	  }
	  break;
	}
      case UE_UNREGISTER:
	{
	  unregisterUser();
	  break;
	}
      case UE_TYPING:
	{
	  debugInfo("User is typing...");
	  m_log_label->setText(m_log_label->toPlainText() + "\n" + message);
	  //no need to parse parameters, going to forward to user
	  
	  QString dest = params.at(0);
	  QString from = params.at(1);

	  debugInfo(dest + "," + from);
	  
	  QByteArray typing_data;
	  QDataStream typing_stream(&typing_data, QIODevice::WriteOnly);
	  typing_stream.setVersion(QDataStream::Qt_4_0);
	  typing_stream << (quint16)0;
	  QStringList typing_params;
	  typing_params << params.at(0) << params.at(1) << params.at(2);
	  typing_stream << m_protocol->constructStream_Server(typing_params,
							      ProtocolStreamType_Server::SERVER_FWD_TYPING);
	  typing_stream.device()->seek(0);

	  DLOG (INFO) << "Sending: " << m_protocol->constructStream_Server(typing_params,
							    ProtocolStreamType_Server::SERVER_FWD_TYPING).toStdString();
	  
	  QTcpSocket *dest_socket = new QTcpSocket(this);
	  QString dest_ip;
	  quint16 dest_port;
	  int index = getIndexOfUEName(dest);
	  if (index != -1) {
	    dest_ip = m_online_users.at(index).ip;
	    dest_port = m_online_users.at(index).rx_port;
	    debugInfo("Going to forward typing info to " +
		      dest_ip + ":" + QString::number(dest_port));
	  } else {
	    LOG (ERROR) << "ERROR: name was not found on server. Returning...";
	    m_block_size=0;
	    return;
	  }
	  dest_socket->connectToHost(QHostAddress(dest_ip), dest_port);
	  if (!dest_socket->waitForConnected(2000)) {
	    debugInfo("ERROR: request timed out");
	  } else {
	    debugInfo("Established connection with client. Sending...");
	    dest_socket->write(typing_data);
	    if (!dest_socket->waitForBytesWritten(5000)) {
	      debugInfo("ERROR: transmission timed out");
	    } else {
	      debugInfo("Success! Typing information was forwarded to destination");
	    }
	    dest_socket->disconnectFromHost();
	  }

	  break;
	}
      default:
	LOG (WARNING) << "Unrecognized stream type";
	break;
      }
    
    }
    //reset m_block_size
    m_block_size=0;
  }