Example #1
0
static void connectHandler(int fd, void *data, int flags)
{
  privateSocketStruct *pss= (privateSocketStruct *)data;
  FPRINTF((stderr, "connectHandler(%d, %p, %d)\n", fd, data, flags));
  if (flags & AIO_X) /* -- exception */
    {
      /* error during asynchronous connect() */
      aioDisable(fd);
      pss->sockError= socketError(fd);
      pss->sockState= Unconnected;
      perror("connectHandler");
    }
  else /* (flags & AIO_W) -- connect completed */
    {
      /* connect() has completed */
      int error= socketError(fd);
      if (error)
	{
	  FPRINTF((stderr, "connectHandler: error %d (%s)\n", error, strerror(error)));
	  pss->sockError= error;
	  pss->sockState= Unconnected;
	}
      else
	{
	  pss->sockState= Connected;
	  setLinger(pss->s, 1);
	}
    }
  notify(pss, CONN_NOTIFY);
}
Example #2
0
bool UdpSocket::listen(uint16_t port)
{
    if (mPriv->listening)
        return false;

    sockaddr_in local;
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = INADDR_ANY;
    local.sin_port = htons(port);
    mPriv->server = socket(AF_INET, SOCK_DGRAM, 0);
    if (mPriv->server == INVALID_SOCKET) {
        const int err = socketError();
        fprintf(stderr, "socket failed: %d %s\n", err, socketErrorMessage(err).c_str());
        return false;
    }
    if (bind(mPriv->server, reinterpret_cast<sockaddr*>(&local), sizeof(local))) {
        const int err = socketError();
        fprintf(stderr, "bind on port %d failed: %d %s\n", port, err, socketErrorMessage(err).c_str());
        close(mPriv->server);
        return false;
    }

    mPriv->start();
    mPriv->listening = true;

    return true;
}
Example #3
0
/* wrapper for socket accpeting */
int socksswitch_accept(const int sock) {
    SOCKET_ADDR_LEN addrlen = sizeof(struct sockaddr_in);
    struct sockaddr_in addr;
    int rc;

    DEBUG_ENTER;

    rc = accept(sock, (struct sockaddr *) &addr, &addrlen);

    /* socket connected */
    if (rc > 0) {
	TRACE_INFO("connect from %s:%i (socket:%i)\n",
		   inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), rc);
    }

    /* error */
    else {
	TRACE_WARNING("failure on connecting (socket:%i err:%i): %s\n",
		      sock, SOCKET_ERROR_CODE, socketError());
	socketError();
    }

    DEBUG_LEAVE;
    return rc;
}
Example #4
0
int_t send(int_t s, const void *data, int_t length, int_t flags)
{
   error_t error;
   size_t written;
   Socket *socket;

   //Make sure the socket descriptor is valid
   if(s < 0 || s >= SOCKET_MAX_COUNT)
   {
      socketError(NULL, ERROR_INVALID_SOCKET);
      return SOCKET_ERROR;
   }

   //Point to the socket structure
   socket = &socketTable[s];

   //Send data
   error = socketSend(socket, data, length, &written, flags << 8);

   //Any error to report?
   if(error)
   {
      socketError(socket, error);
      return SOCKET_ERROR;
   }

   //Return the number of bytes sent
   return written;
}
Example #5
0
SimondConnector::SimondConnector(QObject *parent) :
    QObject(parent), state(Unconnected),
    socket(new QSslSocket(this)),
    timeoutTimer(new QTimer(this)),
    response(new QDataStream(socket)),
    mic(new SoundInput(SOUND_CHANNELS, SOUND_SAMPLERATE, this)),
    passThroughSound(false)
{
    connect(this, SIGNAL(connectionState(ConnectionState)), this, SLOT(setCurrentState(ConnectionState)));
    connect(socket, SIGNAL(readyRead()), this, SLOT(messageReceived()));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError()));
    connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(socketError()));
    connect(socket, SIGNAL(connected()), this, SLOT(connectionEstablished()));
    connect(socket, SIGNAL(encrypted()), this, SLOT(connectionEstablished()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(connectionLost()));

    connect(mic, SIGNAL(error(QString)), this, SIGNAL(error(QString)));
    connect(mic, SIGNAL(microphoneLevel(int,int,int)), this, SIGNAL(microphoneLevel(int,int,int)));
    connect(mic, SIGNAL(listening()), this, SLOT(startRecording()));
    connect(mic, SIGNAL(complete()), this, SLOT(commitRecording()));
    connect(mic, SIGNAL(readyRead()), this, SLOT(soundDataAvailable()));

    connect(timeoutTimer, SIGNAL(timeout()), this, SLOT(timeoutReached()));
    timeoutTimer->setSingleShot(true);
    timeoutTimer->setInterval(SOCKET_TIMEOUT);
}
Example #6
0
int_t recv(int_t s, void *data, int_t size, int_t flags)
{
   error_t error;
   size_t received;
   Socket *socket;

   //Make sure the socket descriptor is valid
   if(s < 0 || s >= SOCKET_MAX_COUNT)
   {
      socketError(NULL, ERROR_INVALID_SOCKET);
      return SOCKET_ERROR;
   }

   //Point to the socket structure
   socket = &socketTable[s];

   //Receive data
   error = socketReceive(socket, data, size, &received, flags << 8);

   //Any error to report?
   if(error)
   {
      socketError(socket, error);
      return SOCKET_ERROR;
   }

   //Return the number of bytes received
   return received;
}
Example #7
0
int_t shutdown(int_t s, int_t how)
{
   error_t error;
   Socket *socket;

   //Make sure the socket descriptor is valid
   if(s < 0 || s >= SOCKET_MAX_COUNT)
   {
      socketError(NULL, ERROR_INVALID_SOCKET);
      return SOCKET_ERROR;
   }

   //Point to the socket structure
   socket = &socketTable[s];

   //Shutdown socket
   error = socketShutdown(socket, how);

   //Any error to report?
   if(error)
   {
      socketError(socket, error);
      return SOCKET_ERROR;
   }

   //Successful processing
   return SOCKET_SUCCESS;
}
void ClientApplication::start() {
	if (!parseCommandLine()) {
		QMessageBox::critical(NULL, applicationName(), trUtf8("Error in the command line arguments. Arguments:\n--host <h>\tConnect to the server on host <h>.\n--local\tRun client locally.\n--port <p>\tUse port <p> to connect to the server."));
		quit();
		return;
	}
	if (mode == mUnspecified) {
		ConnectDialog connectDialog;
		int code = connectDialog.exec();
		if (code == QDialog::Rejected) {
			quit();
			return;
		}
		if (connectDialog.local()) {
			mode = mLocal;
		}
		else {
			mode = mRemote;
			host = connectDialog.host();
			port = connectDialog.port();
		}
	}
	if (mode == mLocal) {
		theTrainer.reset(new Trainer());
		showMainWindow();
	}
	else {
		ProxyTrainer *trainer = new ProxyTrainer();
		theTrainer.reset(trainer);
		connect(trainer, SIGNAL(socketConnected()), SLOT(showMainWindow()));
		connect(trainer, SIGNAL(socketDisconnected()), SLOT(socketDisconnected()));
		connect(trainer, SIGNAL(socketError(QString)), SLOT(socketError(QString)));
		trainer->socketConnectToHost(host, port);
	}
}
Example #9
0
int_t listen(int_t s, int_t backlog)
{
   error_t error;
   Socket *socket;

   //Make sure the socket descriptor is valid
   if(s < 0 || s >= SOCKET_MAX_COUNT)
   {
      socketError(NULL, ERROR_INVALID_SOCKET);
      return SOCKET_ERROR;
   }

   //Point to the socket structure
   socket = &socketTable[s];

   //Place the socket in the listening state
   error = socketListen(socket);

   //Any error to report?
   if(error)
   {
      socketError(socket, error);
      return SOCKET_ERROR;
   }

   //Successful processing
   return SOCKET_SUCCESS;
}
Example #10
0
/* create and bind master socket */
int masterSocket(const int port) {
    int rc;
    struct sockaddr_in addr;

    DEBUG_ENTER;

    /* create master socket */
    rc = socket(AF_INET, SOCK_STREAM, 0);
    if (rc == SOCKET_ERROR) {
	TRACE_ERROR("master socket create (err:%i): %s\n",
		    SOCKET_ERROR_CODE, socketError());
	DEBUG_LEAVE;
	return 0;
    }

    TRACE_VERBOSE("master socket created: %i\n", rc);

    DEBUG;

    /* set socket non blocking */
#ifdef WIN32
    unsigned long nValue = 1;
    ioctlsocket(rc, FIONBIO, &nValue);
#endif

    DEBUG;

    /* bind master socket */
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(port);
    if (bind
	(rc, (struct sockaddr *) &addr,
	 sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
	TRACE_ERROR("failure on binding socket (err:%i): %s\n",
		    SOCKET_ERROR_CODE, socketError());
	DEBUG_LEAVE;
	exit(1);
    }
    TRACE_VERBOSE("master socket bound: %i\n", rc);

    DEBUG;

    /* listen master socket */
    if (listen(rc, 128) == SOCKET_ERROR) {
	TRACE_ERROR("failure on listening (err:%i): %s\n",
		    SOCKET_ERROR_CODE, socketError());
	DEBUG_LEAVE;
	exit(1);
    }

    TRACE_INFO("listening on *:%d (socket:%i)\n", port, rc);
    DEBUG_LEAVE;
    return rc;
}
Example #11
0
void UdpSocketPrivate::run()
{
    sockaddr_in from;
    socklen_t fromlen;
    int ret;
    timeval tv;
    fd_set fds;
    char buf[4096];

    for (;;) {
        tv.tv_sec = 5;
        tv.tv_usec = 0;

        FD_ZERO(&fds);
        FD_SET(server, &fds);

        ret = select(server + 1, &fds, 0, 0, &tv);
        if (ret == SOCKET_ERROR) {
            const int err = socketError();
            fprintf(stderr, "socket failed: %d %s\n", err, UdpSocket::socketErrorMessage(err).c_str());
            return;
        } else if (ret > 0) {
            assert(FD_ISSET(server, &fds));
            bool done;
            do {
                done = true;
                fromlen = sizeof(from);
                ret = recvfrom(server, buf, sizeof(buf), 0, reinterpret_cast<sockaddr*>(&from), &fromlen);
                if (ret == SOCKET_ERROR) {
                    const int err = socketError();
                    if (err == EINTR)
                        done = false;
                    else {
                        fprintf(stderr, "socket recvfrom failed: %d %s\n", err, UdpSocket::socketErrorMessage(err).c_str());
                        return;
                    }
                }
                //printf("got socket data %d\n", ret);
                if (callback && !callback(buf, ret, userData)) {
                    return;
                }
            } while (!done);
        }
        //printf("server wakeup\n");

        MutexLocker locker(&mutex);
        if (stopped)
            return;
    }
}
Example #12
0
void MainWindow::startServer()
{
    if(!db || !db->isOpen()) {
        QMessageBox::information(this, tr("No database"),
                                 tr("you need to configure database for server at first..."));
        return;
    }
    if(server) {
        server->close();
        delete server;
    }

    server = new FSEServer(this);
    server->setDatabase(db);

    connect(server, SIGNAL(acceptError(QAbstractSocket::SocketError)),
            this, SLOT(socketError(QAbstractSocket::SocketError)));
    connect(server, SIGNAL(errorString(QString)),
            this, SLOT(logCollect(QString)));
    connect(server, SIGNAL(debugString(QString)),
            this, SLOT(logCollect(QString)));

    if(server->listen(QHostAddress(IPv4), serverPort)) {
        logCollect(tr("start to listen ") + IPv4 + ":" +QString::number(serverPort));
        stateChange(ServerWorking);
    }
    else {
        qDebug() << "start failed" << server->serverError();
        stopServer();
    }
}
/*!
    Constructs an assistant client with the given \a parent.
    The \a path specifies the path to the Qt Assistant executable.
    If \a path is an empty string the system path (\c{%PATH%} or \c $PATH)
    is used.
*/
QAssistantClient::QAssistantClient( const QString &path, QObject *parent )
    : QObject( parent ), host ( QLatin1String("localhost") )
{
    if ( path.isEmpty() )
        assistantCommand = QLatin1String("assistant");
    else {
        QFileInfo fi( path );
        if ( fi.isDir() )
            assistantCommand = path + QLatin1String("/assistant");
        else
            assistantCommand = path;
    }

#if defined(Q_OS_MAC)
    assistantCommand += QLatin1String(".app/Contents/MacOS/assistant");
#endif

    socket = new QTcpSocket( this );
    connect( socket, SIGNAL(connected()),
            SLOT(socketConnected()) );
    connect( socket, SIGNAL(disconnected()),
            SLOT(socketConnectionClosed()) );
    connect( socket, SIGNAL(error(QAbstractSocket::SocketError)),
             SLOT(socketError()) );
    opened = false;
    proc = new QProcess( this );
    port = 0;
    pageBuffer = QLatin1String("");
    connect( proc, SIGNAL(readyReadStandardError()),
             this, SLOT(readStdError()) );
    connect( proc, SIGNAL(error(QProcess::ProcessError)),
        this, SLOT(procError(QProcess::ProcessError)) );
}
Example #14
0
TcpClient::TcpClient(QObject *parent) : QObject(parent) {
    tcpSocket = new QTcpSocket(this);
    eAuth = new EAuthService(this);
    mainWindow = (MainWindow*)parent;
    windowFacade = mainWindow->getWindowFacade();
    settings = ClientSettings::Instance();

    debugLogger = new DebugLogger();

    if(tcpSocket) {
        connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(socketReadyRead()));
        connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
        connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedFromHost()));
        tcpSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
    }    

    xmlParser = new XmlParserThread(parent);
    connect(this, SIGNAL(addToQueue(QByteArray)), xmlParser, SLOT(addData(QByteArray)));
    connect(this, SIGNAL(updateHighlighterSettings()), xmlParser, SLOT(updateHighlighterSettings()));
    connect(xmlParser, SIGNAL(writeSettings()), this, SLOT(writeSettings()));
    connect(xmlParser, SIGNAL(writeModeSettings()), this, SLOT(writeModeSettings()));

    if(MainWindow::DEBUG) {
        this->loadMockData();
    }
}
Example #15
0
IndiClient::IndiClient(const int &attempts) : mPort(indi::PORT), mAttempts(attempts), mAttempt(1)
{
    connect(&mQTcpSocket, SIGNAL(connected()), SLOT(socketConnected()));
    connect(&mQTcpSocket, SIGNAL(disconnected()), SLOT(socketDisconnected()));
    connect(&mQTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(socketError(QAbstractSocket::SocketError)));
    connect(&mQTcpSocket, SIGNAL(readyRead()), SLOT(socketReadyRead()));
}
Example #16
0
//! [clientConnected]
void TennisServer::clientConnected()
{
    qDebug() << Q_FUNC_INFO << "connect";

    QBluetoothSocket *socket = l2capServer->nextPendingConnection();
    if (!socket)
        return;

    if(clientSocket){
        qDebug() << Q_FUNC_INFO << "Closing socket!";
        delete socket;
        return;
    }

    connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
    connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(socketError(QBluetoothSocket::SocketError)));

    stream = new QDataStream(socket);

    clientSocket = socket;    

    qDebug() << Q_FUNC_INFO << "started";

    emit clientConnected(clientSocket->peerName());
    lagTimer.start();
}
FilezillaAdminConnection::FilezillaAdminConnection(QObject *parent) :
    QObject(parent)
{
    mSocket = new QTcpSocket();
    connect(mSocket, SIGNAL(readyRead()), this, SLOT(bytesToRead()));
    connect(mSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
}
Example #18
0
TSock::TSock(QTcpSocket *sock, QObject *parent) :
  QObject(parent),
  listenPort(0)
{

    if (sock == NULL)
        socket = new QTcpSocket;
    else
        socket = sock;

    connect(socket, SIGNAL(connected()),
            this, SLOT(socketConnected()));

    connect(socket, SIGNAL(disconnected()),
            this, SLOT(socketDisconnected()));

    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(socketError(QAbstractSocket::SocketError)));

    connect(socket, SIGNAL(readyRead()),
            this, SLOT(socketDataReady()));


    connect(&server, SIGNAL(newConnection()),
            this, SLOT(serverConnection()));
}
Example #19
0
void MessageQueue::writeData() {
	if(_sendbuflen==0) {
		// If send buffer is empty, serialize the next message in the queue.
		// The snapshot upload queue has lower priority than the normal queue.
		if(!_sendqueue.isEmpty()) {
			// There are messages in the higher priority queue, send one
			_sendbuflen = _sendqueue.dequeue()->serialize(_sendbuffer);
		} else if(!_snapshot_send.isEmpty()) {
			// If there is nothing in the normal send queue, check if
			// there is something in the lower priority snapshot queue
			SnapshotMode mode(SnapshotMode::SNAPSHOT);
			_sendbuflen = mode.serialize(_sendbuffer);
			_sendbuflen += _snapshot_send.takeFirst()->serialize(_sendbuffer + _sendbuflen);
		}
	}

	if(_sentcount < _sendbuflen) {
		int sent = _socket->write(_sendbuffer+_sentcount, _sendbuflen-_sentcount);
		if(sent<0) {
			// Error
			emit socketError(_socket->errorString());
			return;
		}
		_sentcount += sent;
		if(_sentcount == _sendbuflen) {
			_sendbuflen=0;
			_sentcount=0;
			if(_closeWhenReady)
				close();
			else
				writeData();
		}
	}
}
Example #20
0
SmtpClient::SmtpClient(const QString & host, int port, ConnectionType ct) :
    name("localhost"),
    authMethod(AuthPlain),
    connectionTimeout(5000),
    responseTimeout(5000)
{
    if (ct == TcpConnection)
        this->useSsl = false;
    else if (ct == SslConnection)
        this->useSsl = true;

    if (useSsl == false)
        socket = new QTcpSocket(this);
    else
        socket = new QSslSocket(this);

    this->host = host;
    this->port = port;

    connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(socketError(QAbstractSocket::SocketError)));
    connect(socket, SIGNAL(readyRead()),
            this, SLOT(socketReadyRead()));
}
Example #21
0
/* wrapper for socket closing */
int socksswitch_close(const int sock) {
    char addrstr[256];

    DEBUG_ENTER;

    if (sock <= 0) {
	DEBUG_LEAVE;
	return 0;
    }

    strcpy(addrstr, socksswitch_addr(sock));

    /* disconnect */
    if (shutdown(sock, SD_BOTH) == 0 && SOCKET_CLOSE(sock) == 0)
	TRACE_INFO("disconnected from %s (socket:%i)\n", addrstr, sock);

    /* error */
    else {
	TRACE_WARNING
	    ("failure on closing from %s (socket:%i err:%i): %s\n",
	     addrstr, sock, SOCKET_ERROR_CODE, socketError());
	DEBUG_LEAVE;
	return SOCKET_ERROR;
    }

    DEBUG_LEAVE;
    return 1;
}
Example #22
0
/*!
  Connect to the configured port and host for the device and setting up
  the socket.
*/
void DeviceConnector::connect()
{
    if ( mSocket )  // already connected
        return;
    emit startingConnect();
    loginDone = false;
    mSocket = new QTcpSocket();
    QObject::connect( mSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(socketError()) );
    mSocket->connectToHost( QHostAddress( "10.10.10.20" ), 4245 );
    if ( !mSocket->waitForConnected() )
    {
        emit deviceConnMessage( tr( "Error connecting to device:" ) +
                mSocket->errorString() );
        delete mSocket;
        mSocket = 0;
        return;
    }
    QObject::connect( mSocket, SIGNAL(readyRead()),
            this, SLOT(socketReadyRead()) );
    QObject::connect( mSocket, SIGNAL(disconnected()),
            this, SLOT(socketDisconnected()) );
    emit deviceConnMessage( tr( "Device connected" ) );
    emit finishedConnect();
}
Example #23
0
void SslClient::establish(const QString& host, quint16 port)
{
    threadLock_  = new QMutex();
    threadEvent_ = new QWaitCondition();

    QMutexLocker blocked(threadLock_);
    host_ = host;
    port_ = port;

    start();
    threadEvent_->wait(threadLock_);

    if(ssl_.isNull() || running_ == false)
        Q_ASSERT_X(ssl_.isNull() || running_ == false, "SslClient::establish", "Cannot start SslClient's thread");

    connect(ssl_.data(), SIGNAL(stateChanged(QAbstractSocket::SocketState)), 
            this, SLOT(socketStateChanged(QAbstractSocket::SocketState)), Qt::DirectConnection);
    connect(ssl_.data(), SIGNAL(encrypted()), 
            this, SLOT(socketEncrypted()), Qt::DirectConnection);
    connect(ssl_.data(), SIGNAL(error(QAbstractSocket::SocketError)), 
            this, SLOT(socketError(QAbstractSocket::SocketError)), Qt::DirectConnection);
    connect(ssl_.data(), SIGNAL(sslErrors(QList<QSslError>)), 
            this, SLOT(sslErrors(QList<QSslError>)), Qt::DirectConnection);
    connect(ssl_.data(), SIGNAL(readyRead()), 
            this, SLOT(socketReadyRead()), Qt::DirectConnection);

    ConfigureForLMAX();
}
void Connection::connect(QString h,int p) {
    host=h;
    port=p;

    // cleanup previous object, if any
    if (tcpSocket) {
        delete tcpSocket;
    }

    tcpSocket=new QTcpSocket(this);

    QObject::connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(socketError(QAbstractSocket::SocketError)));

    QObject::connect(tcpSocket, SIGNAL(connected()),
            this, SLOT(connected()));

    QObject::connect(tcpSocket, SIGNAL(disconnected()),
            this, SLOT(disconnected()));

    QObject::connect(tcpSocket, SIGNAL(readyRead()),
            this, SLOT(socketData()));

    // set the initial state
    state=READ_HEADER_TYPE;
    // cleanup dirty value eventually left from previous usage
    bytes=0;
    qDebug() << "Connection::connect: connectToHost: " << host << ":" << port;
    tcpSocket->connectToHost(host,port);

}
Example #25
0
bool MjpegClient::connectTo(const QString& host, int port, QString url, const QString& user, const QString& pass)
{
    if(url.isEmpty())
        url = "/";

    m_host = host;
    m_port = port > 0 ? port : 80;
    m_url = url;
    m_user = user;
    m_pass = pass;

    if(m_socket)
    {
        m_socket->abort();
        delete m_socket;
        m_socket = 0;
    }

    m_socket = new QTcpSocket(this);
    connect(m_socket, SIGNAL(readyRead()),    this,   SLOT(dataReady()));
    connect(m_socket, SIGNAL(disconnected()), this,   SLOT(lostConnection()));
    connect(m_socket, SIGNAL(disconnected()), this, SIGNAL(socketDisconnected()));
    connect(m_socket, SIGNAL(connected()),    this, SIGNAL(socketConnected()));
    connect(m_socket, SIGNAL(connected()),    this,   SLOT(connectionReady()));
    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SIGNAL(socketError(QAbstractSocket::SocketError)));
    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(lostConnection(QAbstractSocket::SocketError)));

    m_socket->connectToHost(host,port);
    m_socket->setReadBufferSize(1024 * 1024);

    return true;
}
Example #26
0
void MainWindow::on_connectButton_clicked()
{
    if(m_connectionState == ConnectionState::Disconnected)
    {
        QString host = ui->hostLineEdit->text();
        quint16 port = ui->portSpinBox->value();
        QString name = ui->nameLineEdit->text();

        m_tcpClient.reset(new nc::TcpClient);
        m_gameState.reset(new GameState(host, port, name, *m_tcpClient.get()));

        connect(m_tcpClient.get(), SIGNAL(messageRead(QByteArray)), m_gameState.get(), SLOT(onInboundMessage(QByteArray)));
        connect(m_gameState.get(), SIGNAL(outboundMessage(QByteArray)), m_tcpClient.get(), SLOT(writeMessage(QByteArray)));
        connect(m_gameState.get(), SIGNAL(chatMessageReceived(QString)), this, SLOT(onChatMessageReceived(QString)));
        connect(m_gameState.get(), SIGNAL(disconnectedFromServer(QString)), this, SLOT(onDisconnected(QString)));
        connect(this, SIGNAL(chatMessageSent(QString)), m_gameState.get(), SLOT(onChatMessageSent(QString)));
        connect(m_tcpClient.get(), SIGNAL(connected()), this, SLOT(onConnected()));
        connect(m_tcpClient.get(), SIGNAL(disconnected()), this, SLOT(onDisconnected()));
        connect(m_tcpClient.get(), SIGNAL(socketError(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));

        m_tcpClient->connectToHost(host, port);
        changeConnectionState(ConnectionState::Connecting);

        qDebug() << "Connecting.";
        appendHtml(QString("<b>Connecting to %1:%2.</b><br>").arg(host).arg(port));
    }
    else
    {
        m_tcpClient->disconnectFromHost();
    }
}
Example #27
0
void SocketImpl::connect(const SocketAddress& address, const Poco::Timespan& timeout)
{
	if (_sockfd == POCO_INVALID_SOCKET)
	{
		init(address.af());
	}
	setBlocking(false);
	try
	{
#if defined(POCO_VXWORKS)
		int rc = ::connect(_sockfd, (sockaddr*) address.addr(), address.length());
#else
		int rc = ::connect(_sockfd, address.addr(), address.length());
#endif
		if (rc != 0)
		{
			int err = lastError();
			if (err != POCO_EINPROGRESS && err != POCO_EWOULDBLOCK)
				error(err, address.toString());
			if (!poll(timeout, SELECT_READ | SELECT_WRITE | SELECT_ERROR))
				throw Poco::TimeoutException("connect timed out", address.toString());
			err = socketError();
			if (err != 0) error(err);
		}
	}
	catch (Poco::Exception&)
	{
		setBlocking(true);
		throw;
	}
	setBlocking(true);
}
Example #28
0
void PingPong::clientConnected()
{
    //! [Initiating server socket]
    if (!m_serverInfo->hasPendingConnections()) {
        setMessage("FAIL: expected pending server connection");
        return;
    }
    socket = m_serverInfo->nextPendingConnection();
    if (!socket)
        return;
    socket->setParent(this);
    connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
    connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)),
            this, SLOT(socketError(QBluetoothSocket::SocketError)));
    //! [Initiating server socket]
    setMessage(QStringLiteral("Client connected."));

    QByteArray size;
    size.setNum(m_boardWidth);
    size.append(' ');
    QByteArray size1;
    size1.setNum(m_boardHeight);
    size.append(size1);
    size.append(" \n");
    socket->write(size.constData());

}
Example #29
0
BtLocalDevice::BtLocalDevice(QObject *parent) :
    QObject(parent), securityFlags(QBluetooth::NoSecurity)
{
    localDevice = new QBluetoothLocalDevice(this);
    connect(localDevice, SIGNAL(error(QBluetoothLocalDevice::Error)),
            this, SIGNAL(error(QBluetoothLocalDevice::Error)));
    connect(localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)),
            this, SIGNAL(hostModeStateChanged()));
    connect(localDevice, SIGNAL(pairingFinished(QBluetoothAddress,QBluetoothLocalDevice::Pairing)),
            this, SLOT(pairingFinished(QBluetoothAddress,QBluetoothLocalDevice::Pairing)));
    connect(localDevice, SIGNAL(deviceConnected(QBluetoothAddress)),
            this, SLOT(connected(QBluetoothAddress)));
    connect(localDevice, SIGNAL(deviceDisconnected(QBluetoothAddress)),
            this, SLOT(disconnected(QBluetoothAddress)));
    connect(localDevice, SIGNAL(pairingDisplayConfirmation(QBluetoothAddress,QString)),
            this, SLOT(pairingDisplayConfirmation(QBluetoothAddress,QString)));

    if (localDevice->isValid()) {
        deviceAgent = new QBluetoothDeviceDiscoveryAgent(this);
        connect(deviceAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
                this, SLOT(deviceDiscovered(QBluetoothDeviceInfo)));
        connect(deviceAgent, SIGNAL(finished()),
                this, SLOT(discoveryFinished()));
        connect(deviceAgent, SIGNAL(error(QBluetoothDeviceDiscoveryAgent::Error)),
                this, SLOT(discoveryError(QBluetoothDeviceDiscoveryAgent::Error)));
        connect(deviceAgent, SIGNAL(canceled()),
                this, SLOT(discoveryCanceled()));

        serviceAgent = new QBluetoothServiceDiscoveryAgent(this);
        connect(serviceAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)),
                this, SLOT(serviceDiscovered(QBluetoothServiceInfo)));
        connect(serviceAgent, SIGNAL(finished()),
                this, SLOT(serviceDiscoveryFinished()));
        connect(serviceAgent, SIGNAL(canceled()),
                this, SLOT(serviceDiscoveryCanceled()));
        connect(serviceAgent, SIGNAL(error(QBluetoothServiceDiscoveryAgent::Error)),
                this, SLOT(serviceDiscoveryError(QBluetoothServiceDiscoveryAgent::Error)));

        socket = new QBluetoothSocket(SOCKET_PROTOCOL, this);
        connect(socket, SIGNAL(stateChanged(QBluetoothSocket::SocketState)),
                this, SLOT(socketStateChanged(QBluetoothSocket::SocketState)));
        connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)),
                this, SLOT(socketError(QBluetoothSocket::SocketError)));
        connect(socket, SIGNAL(connected()), this, SLOT(socketConnected()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
        connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
        setSecFlags(socket->preferredSecurityFlags());

        server = new QBluetoothServer(SOCKET_PROTOCOL, this);
        connect(server, SIGNAL(newConnection()), this, SLOT(serverNewConnection()));
        connect(server, SIGNAL(error(QBluetoothServer::Error)),
                this, SLOT(serverError(QBluetoothServer::Error)));
    } else {
        deviceAgent = 0;
        serviceAgent = 0;
        socket = 0;
        server = 0;
    }
}
Example #30
0
ExtPlaneConnection::ExtPlaneConnection(QObject *parent) : QTcpSocket(parent), updateInterval(0.333) {
    connect(this, SIGNAL(connected()), this, SLOT(socketConnected()));
    connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
    connect(this, SIGNAL(readyRead()), this, SLOT(readClient()));
    connect(&reconnectTimer, SIGNAL(timeout()), this, SLOT(tryReconnect()));
    server_ok = false;
    enableSimulatedRefs = false;
}