Esempio n. 1
0
void ServerPool::newTcpConnection(int socket)
{
    QTcpSocket *qsock = new QTcpSocket(this);
    qsock->setSocketDescriptor(socket);
    emit newConnection(qsock);
}
Esempio n. 2
0
CmdServer::CmdServer()
{
	connect(&listenner_, SIGNAL(newConnection()), SLOT(onNewConnection()));
	listenner_.listen(QHostAddress::LocalHost, connectPort);
}
Esempio n. 3
0
void Server::incomingConnection(qintptr socketDescriptor)
{
    Connection *connection = new Connection(this);
    connection->setSocketDescriptor(socketDescriptor);
    emit newConnection(connection);
}
Esempio n. 4
0
void eServerSocket::notifier(int)
{
	int clientfd;
	socklen_t clientlen;
// handle multiple socket types...
	union
	{
		sockaddr sock;
		sockaddr_in sock_in;
		sockaddr_in6 sock_in6;
	} client_addr;

	char straddr[INET6_ADDRSTRLEN];

#ifdef DEBUG_SERVERSOCKET
	eDebug("[eServerSocket] incoming connection!");
#endif

	clientlen = sizeof(client_addr);
	clientfd = accept(getDescriptor(), &client_addr.sock, &clientlen);
	if (clientfd < 0)
	{
		eDebug("[eServerSocket] error on accept: %m");
		return;
	}

	switch(client_addr.sock.sa_family)
	{
		case(AF_LOCAL):
		{
			strRemoteHost = "(local)";
			break;
		}

		case(AF_INET):
		{
			strRemoteHost = inet_ntop(AF_INET, &client_addr.sock_in.sin_addr, straddr, sizeof(straddr));
			break;
		}

		case(AF_INET6):
		{
			if (IN6_IS_ADDR_V4MAPPED(&client_addr.sock_in6.sin6_addr)) {
// Just get the normal IPv4 reprsentation by fudging in the IPv4 address part
				strRemoteHost = inet_ntop(PF_INET, (sockaddr_in *)&client_addr.sock_in6.sin6_addr.s6_addr[12], straddr, sizeof(straddr));
			}
			else
			{
				strRemoteHost = inet_ntop(AF_INET6, &client_addr.sock_in6.sin6_addr, straddr, sizeof(straddr));
			}
			break;
		}

		default:
		{
			strRemoteHost = "(error)";
			break;
		}
	}

	newConnection(clientfd);
}
Esempio n. 5
0
int acceptBrowserServerConnectionToStream(int browserListener, fd_set * master, int * fdmax, stream_s **stream, command_line_s *commandLine){
  socklen_t addr_size;

  struct sockaddr_in browser_addr;
  connection_list_s *connection = NULL;

  int browser_sock;
  int server_sock;
  struct sockaddr_in client_addr;
  struct sockaddr_in server_addr;

  char str[50];
  addr_size = sizeof(browser_addr);

  log_msg(log, "Attempting to accept connection\n");

  if(*stream == NULL){//new stream!
    memcpy(&client_addr.sin_addr, &commandLine->fake_ip, sizeof(struct in_addr));
    memcpy(&server_addr.sin_addr, &commandLine->www_ip, sizeof(struct in_addr));
    client_addr.sin_family = AF_INET;
    server_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(RAND_PORT);
    server_addr.sin_port = htons(SERV_PORT);

    memset(client_addr.sin_zero, '\0', sizeof(client_addr.sin_zero));
    memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero));

    *stream = newStream(&client_addr, &server_addr, commandLine->alpha);
  }
  else{
    memcpy(&client_addr, &(*stream)->client_addr, addr_size);
    memcpy(&server_addr, &(*stream)->server_addr, addr_size);
  }

  //create new socket to server//CHECK FOR ERRORS
  if ((server_sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) printf("socket failed\n");

  //change port number to unoccupied one, client_addr should be copied from stream
  client_addr.sin_port = htons(ntohs(client_addr.sin_port) + port_offset);
  INC_POFFSET();

  if (bind(server_sock, (struct sockaddr*)&client_addr, addr_size) < 0) {
    char tmp[80];
    inet_ntop(AF_INET, &client_addr.sin_addr, tmp, 80);
    log_msg(log, "Socket: %d\nBind addr: %s\nport: %d\n", server_sock, tmp, ntohs(client_addr.sin_port)); 
    log_msg(log, "Bind failed\n");
    perror("bind"); 
    exit(EXIT_FAILURE);
  }

  if (connect(server_sock, (struct sockaddr*)&(*stream)->server_addr, addr_size))
		log_msg(log, "Connect failed\n");

  //accept new socket to browser
  if ((browser_sock = accept(browserListener, (struct sockaddr *) &browser_addr,
                            &addr_size)) == -1)
    {
      close(browserListener);
      log_msg(log, "Error accepting connection.");
      return EXIT_FAILURE;
    }
  
  //create new connection adn add it to stream
  connection = newConnection(browser_sock, server_sock);
  addConnectionToStream(connection, *stream);
  log_msg(log, "Added connections on sockets b:%d,s:%d\n",connection->browser_sock, connection->server_sock); 


  //Add socket to browser to fdset
  FD_SET(browser_sock, master); // add new socket to master set
  if (browser_sock > *fdmax) {    // keep track of the max
    *fdmax = browser_sock;
  }

  //Add socket to server to master
  FD_SET(server_sock, master); // add new socket to master set
  if (server_sock > *fdmax) {    // keep track of the max
    *fdmax = server_sock;
  }

  inet_ntop(AF_INET, (void *)(&(browser_addr.sin_addr)), str, 50);
  log_msg(log, "Accepted connection from %s", str);
  return 0;
}
Esempio n. 6
0
void LocalPeer::listen()
{
	server_->listen(socket_name_);
    QObject::connect(server_, SIGNAL(newConnection()), SLOT(receiveConnection()), Qt::QueuedConnection);
}
void LoadPointLineGeometry::_updateOutputData()
{
  _outPositionsList.clearList();
  _outConnectionsList.clearList();

  std::string newSetFilter = "";
  std::string newSetName = "";
  int newSetType = 0;

  std::string filterString = _filterFld->getStringValue();

  std::string numberDelimiter = _numberDelimiterFld->getStringValue();

  if (_numberDelimiterSpaceFld->getBoolValue())
  {
    numberDelimiter = " ";
  }

  std::string decimalSeparator = _decimalSeparatorFld->getStringValue();

  for(StringVector::iterator it = _inputFileLinesVector.begin(); it != _inputFileLinesVector.end(); ++it) 
  {
    std::string thisLine = *it;

    StringVector thisDataLineComponents = mlPDF::PDFTools::stringSplit(thisLine, " ", false);
    size_t thisDataLineNumComponents = thisDataLineComponents.size();

    if (thisDataLineNumComponents > 0)
    {
      // Check if new set definition is started
      if (thisDataLineNumComponents > 1)  // Must be at least a a <Tag> <Type> {<Name>} pair/triple
      {
        std::string firstComponent = thisDataLineComponents[0];

        if (isalpha(firstComponent[0]))
        {
          newSetFilter = firstComponent;
          newSetType = mlPDF::stringToInt(thisDataLineComponents[1]);

          if (thisDataLineNumComponents > 2)
          {
            newSetName = "";

            // Append all remaining fragments to the name
            for (size_t i = 2; i < thisDataLineNumComponents; i++)
            {
              if (newSetName != "")
              {
                newSetName += " ";
              }

              newSetName += thisDataLineComponents[i];
            }
          }
          else
          {
            newSetName = "";
          }

          continue;
        }
      }

      if ((filterString == "") || (filterString == newSetFilter))
      {
        // If it is a list of connections
        if (thisDataLineNumComponents == 2)
        {
          // Add point (only the first 3 components)         
          int start = mlPDF::stringToInt(thisDataLineComponents[0]);
          int end = mlPDF::stringToInt(thisDataLineComponents[1]);

          IndexPair newConnection(start, end, newSetType, newSetName.c_str());
          _outConnectionsList.appendItem(newConnection);
        }
        // If it is a list of positions
        else if (thisDataLineNumComponents > 2)
        {
          // Add point (only the first 3 components)         
          double x = mlPDF::stringToDouble(thisDataLineComponents[0]);
          double y = mlPDF::stringToDouble(thisDataLineComponents[1]);
          double z = mlPDF::stringToDouble(thisDataLineComponents[2]);

          XMarker newPosition(Vector6(x, y, z, 0, 0, 0), newSetType, newSetName.c_str());
          _outPositionsList.appendItem(newPosition);
        }

      }

    } // if (thisDataLineNumComponents > 0)

  } // for(StringVector::iterator it

  // Deselect items
  _outPositionsList.selectItemAt(-1);
  _outConnectionsList.selectItemAt(-1);

  _createFibers();

  if (_autoAddToCacheFld->getBoolValue())
  {
    _addToCache();
  }

  // Set validation fields
  _positionsLoadedFld->setBoolValue(_outPositionsList.size() > 0);
  _connectionsLoadedFld->setBoolValue(_outConnectionsList.size() > 0);

  // Update output
  _outPositionsListFld->touch();
  _outConnectionsListFld->touch();
  _outFibersFld->touch();
}
Esempio n. 8
0
/**
 * handle incoming tcp data from client connections in the admin process
 */
static void incomingFromClient(evutil_socket_t socket, short eventType, void* vconn)
{
    struct Connection* conn = (struct Connection*) vconn;
    struct AngelContext* context = conn->context;

    uint8_t buf[PipeInterface_MAX_MESSAGE_SIZE + PipeInterface_PADDING];
    uint32_t connNumber = conn - context->connections;

    struct Message message = {
        .bytes = buf + PipeInterface_PADDING,
        .length = PipeInterface_MAX_MESSAGE_SIZE,
        .padding = PipeInterface_PADDING
    };
    ssize_t result = recv(socket, message.bytes, message.length, 0);

    if (result > 0) {
        message.length = result;
        sendToCore(&message, connNumber, context);
    } else if (result < 0 && Errno_get() == Errno_EAGAIN) {
        return;
    } else {
        // The return value will be 0 when the peer has performed an orderly shutdown.
        EVUTIL_CLOSESOCKET(conn->socket);
        event_free(conn->read);
        conn->read = NULL;
        // send close channel
        message.length = 0;
        sendToCore(&message, connNumber, context);
        // set conn->socket = -1 later when we recv close ACK
    }
}

static struct Connection* newConnection(struct AngelContext* context, evutil_socket_t fd)
{
    struct Connection* conn = NULL;
    for (int i = 0; i < Angel_MAX_CONNECTIONS; i++) {
        if (context->connections[i].read == NULL && context->connections[i].socket == -1) {
            conn = &context->connections[i];
            break;
        }
    }

    if (!conn) {
        return NULL;
    }

    conn->read = event_new(context->eventBase, fd, EV_READ | EV_PERSIST, incomingFromClient, conn);
    conn->socket = fd;
    conn->context = context;

    if (!conn->read) {
        return NULL;
    }

    event_add(conn->read, NULL);
    return conn;
}

static void acceptConn(evutil_socket_t socket, short eventType, void* vcontext)
{
    struct AngelContext* context = (struct AngelContext*) vcontext;

    struct sockaddr_storage ss;
    ev_socklen_t slen = sizeof(ss);
    evutil_socket_t fd = accept(socket, (struct sockaddr*)&ss, &slen);
    if (fd < 0) {
        perror("acceptConn() fd < 0");
        return;
    } else if (fd > (evutil_socket_t) FD_SETSIZE) {
        EVUTIL_CLOSESOCKET(fd);
        return;
    }

    evutil_make_socket_nonblocking(fd);

    struct Connection* conn = newConnection(context, fd);
    if (!conn) {
        EVUTIL_CLOSESOCKET(fd);
    }
}

void Angel_start(String* pass,
                 evutil_socket_t tcpSocket,
                 struct Interface* coreIface,
                 struct event_base* eventBase,
                 struct Log* logger,
                 struct Allocator* alloc)
{
    struct AngelContext contextStore;
    struct AngelContext* context = &contextStore;
    Bits_memset(context, 0, sizeof(struct AngelContext));

    for (int i = 0; i < Angel_MAX_CONNECTIONS; i++) {
        context->connections[i].socket = -1;
    }
    context->eventBase = eventBase;
    context->logger = logger;

    context->coreIface = coreIface;
    context->coreIface->receiveMessage = receiveMessage;
    context->coreIface->receiverContext = context;

    context->socketEvent =
        event_new(context->eventBase, tcpSocket, EV_READ | EV_PERSIST, acceptConn, context);
    event_add(context->socketEvent, NULL);

    event_base_dispatch(context->eventBase);
}
Esempio n. 9
0
/** Constructor. Parses the command-line arguments, resets Rshare's
 * configuration (if requested), and sets up the GUI style and language
 * translation. */
Rshare::Rshare(QStringList args, int &argc, char **argv, const QString &dir)
: QApplication(argc, argv)
{
  mStartupTime = QDateTime::currentDateTime();
  localServer = NULL;

  //Initialize connection to LocalServer to know if other process runs.
  {
    QString serverName = QString(TARGET);

    if (!args.isEmpty()) {
      // load into shared memory
      QBuffer buffer;
      buffer.open(QBuffer::ReadWrite);
      QDataStream out(&buffer);
      out << args;
      int size = buffer.size();

      QSharedMemory newArgs;
      newArgs.setKey(serverName + "_newArgs");
      if (newArgs.isAttached()) newArgs.detach();

      if (!newArgs.create(size)) {
        std::cerr << "(EE) Rshare::Rshare Unable to create shared memory segment of size:"
                  << size << " error:" << newArgs.errorString().toStdString() << "." << std::endl;
#ifdef Q_OS_UNIX
        std::cerr << "Look with `ipcs -m` for nattch==0 segment. And remove it with `ipcrm -m 'shmid'`." << std::endl;
        //No need for windows, as it removes shared segment directly even when crash.
#endif
        newArgs.detach();
        ::exit(EXIT_FAILURE);
      }
      newArgs.lock();
      char *to = (char*)newArgs.data();
      const char *from = buffer.data().data();
      memcpy(to, from, qMin(newArgs.size(), size));
      newArgs.unlock();

      // Connect to the Local Server of the main process to notify it
      // that a new process had been started
      QLocalSocket localSocket;
      localSocket.connectToServer(QString(TARGET));

      std::cerr << "Rshare::Rshare waitForConnected to other instance." << std::endl;
      if( localSocket.waitForConnected(100) )
      {
        std::cerr << "Rshare::Rshare Connection etablished. Waiting for disconnection." << std::endl;
        localSocket.waitForDisconnected(1000);
        newArgs.detach();
        std::cerr << "Rshare::Rshare Arguments was sended." << std::endl
                  << " To disable it, in Options - General - Misc," << std::endl
                  << " uncheck \"Use Local Server to get new Arguments\"." << std::endl;
        ::exit(EXIT_SUCCESS); // Terminate the program using STDLib's exit function
      }
      newArgs.detach();
    }
    // No main process exists
    // Or started without arguments
    // So we start a Local Server to listen for connections from new process
    localServer= new QLocalServer();
    QObject::connect(localServer, SIGNAL(newConnection()), this, SLOT(slotConnectionEstablished()));
    updateLocalServer();
  }

#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0)
  qInstallMessageHandler(qt_msg_handler);
#else
  qInstallMsgHandler(qt_msg_handler);
#endif

#ifndef __APPLE__

  /* set default window icon */
  setWindowIcon(QIcon(":/icons/logo_128.png"));

#endif

  mBlink = true;
  QTimer *timer = new QTimer(this);
  timer->setInterval(500);
  connect(timer, SIGNAL(timeout()), this, SLOT(blinkTimer()));
  timer->start();

  timer = new QTimer(this);
  timer->setInterval(60000);
  connect(timer, SIGNAL(timeout()), this, SIGNAL(minuteTick()));
  timer->start();

  /* Read in all our command-line arguments. */
  parseArguments(args);

  /* Check if we're supposed to reset our config before proceeding. */
  if (_args.contains(ARG_RESET)) {
    Settings->reset();
  }
  
  /* Handle the -loglevel and -logfile options. */
  if (_args.contains(ARG_LOGFILE))
    _log.open(_args.value(ARG_LOGFILE));
  if (_args.contains(ARG_LOGLEVEL)) {
    _log.setLogLevel(Log::stringToLogLevel(
                      _args.value(ARG_LOGLEVEL)));
    if (!_args.contains(ARG_LOGFILE))
      _log.open(stdout);
  }
  if (!_args.contains(ARG_LOGLEVEL) && 
      !_args.contains(ARG_LOGFILE))
    _log.setLogLevel(Log::Off);

  /* config directory */
  useConfigDir = false;
  if (dir != "")
  {
  	setConfigDirectory(dir);
  }

  /** Initialize support for language translations. */
  //LanguageSupport::initialize();

  resetLanguageAndStyle();

  /* Switch off auto shutdown */
  setQuitOnLastWindowClosed ( false );

	/* Initialize GxsIdDetails */
	GxsIdDetails::initialize();
}
void
SpotifyListenerWin::loop()
{
    m_windowTitle.clear();

    EnumWindows( SpotifyListenerWin::callback, reinterpret_cast<LPARAM>(this) );

    // stopped =
    // paused = Spotify
    // playing = Spotify - Allo, Darlin' – Kiss Your Lips

    State playerState = Stopped;

    if ( m_windowTitle.startsWith( "Spotify" ) )
    {
        if ( !m_connection )
            emit newConnection( m_connection = new SpotifyConnection );

        QRegExp re( QString( "^Spotify - (.+) %1 (.+)").arg( QChar( 0x2013 )  ), Qt::CaseSensitive, QRegExp::RegExp2 );

        playerState = re.indexIn( m_windowTitle ) == 0 ? Playing : Paused;

        if ( m_lastPlayerState != playerState )
        {
            if ( playerState == Stopped )
            {
                m_connection->stop();
                m_lastTrack = Track();
            }
            else if ( playerState == Paused )
            {
                if ( m_lastPlayerState == Playing )
                    m_connection->pause();
            }
            else if ( playerState == Playing )
            {
                MutableTrack t;
                t.setTitle( re.capturedTexts().at( 2 ) );
                t.setArtist( re.capturedTexts().at( 1 ) );
                // we don't know the duration, but we don't display it so just guess
                t.setDuration( 320 );

                if ( m_lastPlayerState == Paused && t == m_lastTrack )
                    m_connection->resume();
                else
                    m_connection->start( t );

                m_lastTrack = t;
            }
        }
        else if ( playerState == Playing )
        {
            // when going from one song to the next we stay in the play state
            MutableTrack t;
            t.setTitle( re.capturedTexts().at( 2 ) );
            t.setArtist( re.capturedTexts().at( 1 ) );
            // we don't know the duration, but we don't display it so just guess
            t.setDuration( 320 );

            if ( t != m_lastTrack )
                m_connection->start( t );

            m_lastTrack = t;
        }
    }
    else
    {
        if ( m_lastPlayerState == Playing || m_lastPlayerState == Paused )
            m_connection->stop();

        delete m_connection;
    }

    m_lastPlayerState = playerState;
}
Esempio n. 11
0
void QWsServer::dataReceived()
{
	QTcpSocket * tcpSocket = qobject_cast<QTcpSocket*>( sender() );
	if (tcpSocket == 0)
		return;

	bool allHeadersFetched = false;

	const QLatin1String emptyLine("\r\n");

	while ( tcpSocket->canReadLine() )
	{
		QString line = tcpSocket->readLine();

		if (line == emptyLine)
		{
			allHeadersFetched = true;
			break;
		}

		headerBuffer[ tcpSocket ].append(line);
	}

	if (!allHeadersFetched)
	    return;

	QString request( headerBuffer[ tcpSocket ].join("") );

	QRegExp regExp;
	regExp.setMinimal( true );
	
	// Extract mandatory datas
	// Version
	regExp.setPattern( QWsServer::regExpVersionStr );
	regExp.indexIn(request);
	QString versionStr = regExp.cap(1);
	EWebsocketVersion version;
	if ( ! versionStr.isEmpty() )
	{
		version = (EWebsocketVersion)versionStr.toInt();
	}
	else if ( tcpSocket->bytesAvailable() >= 8 )
	{
		version = WS_V0;
		request.append( tcpSocket->read(8) );
	}
	else
	{
		version = WS_VUnknow;
	}

	// Resource name
	regExp.setPattern( QWsServer::regExpResourceNameStr );
	regExp.indexIn(request);
	QString resourceName = regExp.cap(1);
	
	// Host (address & port)
	regExp.setPattern( QWsServer::regExpHostStr );
	regExp.indexIn(request);
	QString host = regExp.cap(1);
	QStringList hostTmp = host.split(':');
	QString hostAddress = hostTmp[0];
	QString hostPort;
	if ( hostTmp.size() > 1 )
        hostPort = hostTmp.last(); // fix for IPv6
	
	// Key
	QString key, key1, key2, key3;
	if ( version >= WS_V4 )
	{
		regExp.setPattern( QWsServer::regExpKeyStr );
		regExp.indexIn(request);
		key = regExp.cap(1);
	}
	else
	{
		regExp.setPattern( QWsServer::regExpKey1Str );
		regExp.indexIn(request);
		key1 = regExp.cap(1);
		regExp.setPattern( QWsServer::regExpKey2Str );
		regExp.indexIn(request);
		key2 = regExp.cap(1);
		regExp.setPattern( QWsServer::regExpKey3Str );
		regExp.indexIn(request);
		key3 = regExp.cap(1);
	}
	
	////////////////////////////////////////////////////////////////////

	// If the mandatory fields are not specified, we abord the connection to the Websocket server
	if ( version == WS_VUnknow || resourceName.isEmpty() || hostAddress.isEmpty() || ( key.isEmpty() && ( key1.isEmpty() || key2.isEmpty() || key3.isEmpty() ) ) )
	{
		// Send bad request response
		QString response = QWsServer::composeBadRequestResponse( QList<EWebsocketVersion>() << WS_V6 << WS_V7 << WS_V8 << WS_V13 );
		tcpSocket->write( response.toUtf8() );
		tcpSocket->flush();
		return;
	}
	
	////////////////////////////////////////////////////////////////////
	
	// Extract optional datas

	// Origin
	regExp.setPattern( QWsServer::regExpOriginStr );
	if ( regExp.indexIn(request) == -1 )
	{
		regExp.setPattern( QWsServer::regExpOrigin2Str );
		regExp.indexIn(request);
	}
	QString origin = regExp.cap(1);

	// Protocol
	regExp.setPattern( QWsServer::regExpProtocolStr );
	regExp.indexIn(request);
	QString protocol = regExp.cap(1);

	// Extensions
	regExp.setPattern( QWsServer::regExpExtensionsStr );
	regExp.indexIn(request);
	QString extensions = regExp.cap(1);
	
	////////////////////////////////////////////////////////////////////
	
	// Compose opening handshake response
	QString response;

	if ( version >= WS_V6 )
	{
		QString accept = computeAcceptV4( key );
		response = QWsServer::composeOpeningHandshakeResponseV6( accept, protocol );
	}
	else if ( version >= WS_V4 )
	{
		QString accept = computeAcceptV4( key );
		QString nonce = generateNonce();
		response = QWsServer::composeOpeningHandshakeResponseV4( accept, nonce, protocol );
	}
	else
	{
		QString accept = computeAcceptV0( key1, key2, key3 );
		response = QWsServer::composeOpeningHandshakeResponseV0( accept, origin, hostAddress, hostPort, resourceName , protocol );
	}
	
	// Handshake OK, disconnect readyRead
	disconnect( tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()) );

	// Send opening handshake response
	if ( version == WS_V0 )
        tcpSocket->write( response.toLatin1() );
	else
		tcpSocket->write( response.toUtf8() );
	tcpSocket->flush();

	QWsSocket * wsSocket = new QWsSocket( this, tcpSocket, version );
	wsSocket->setResourceName( resourceName );
	wsSocket->setHost( host );
	wsSocket->setHostAddress( hostAddress );
	wsSocket->setHostPort( hostPort.toInt() );
	wsSocket->setOrigin( origin );
	wsSocket->setProtocol( protocol );
	wsSocket->setExtensions( extensions );
	wsSocket->serverSideSocket = true;
	
	// ORIGINAL CODE
	//int socketDescriptor = tcpSocket->socketDescriptor();
	//incomingConnection( socketDescriptor );
	
	// CHANGED CODE FOR LINUX COMPATIBILITY
	addPendingConnection( wsSocket );
	emit newConnection();
}
Esempio n. 12
0
Server::Server(QObject *parent) :
    QObject(parent)
{
    mServer = new QTcpServer(this);
    connect(mServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
}
Esempio n. 13
0
GraspitProtobufServer::GraspitProtobufServer(unsigned int port_num, QObject * parent ):
    QTcpServer(parent)
{
    connect(this, SIGNAL(newConnection()), this, SLOT(onConnection()));
    this->listen(QHostAddress::Any,port_num);
}
Esempio n. 14
0
Server::Server(QObject *parent)
: QTcpServer(parent)
{
    connect(this, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
}
Esempio n. 15
0
void QWSServerSocket::incomingConnection(int socketDescriptor)
{
    inboundConnections.append( socketDescriptor );
    emit newConnection();
}
Esempio n. 16
0
void QFCgiTcpConnectionBuilder::onNewConnection() {
  QFCgi *fcgi = qobject_cast<QFCgi*>(parent());
  QTcpSocket *so = this->server->nextPendingConnection();
  QFCgiConnection *connection = new QFCgiConnection(so, fcgi);
  emit newConnection(connection);
}
Esempio n. 17
0
ServerNForm::ServerNForm( Q_UINT16 port )
{
    ///// ** KeyPad Define for Authorization ** ///////////////////
    keypad = new KeyPad();
    keypad->show();

    ///// ** Initializing ETC ** //////////////////////////////////
	simServer = new QTcpServer(this);
	if(!simServer->listen(QHostAddress::Any, port))
	{
		qDebug("****** Unable to start the server ******");
		simServer->close();
	}
	else
	{
		qDebug("SimpleServer is initialized ");
	}
    newClientFlag = -1;

    infoText->append( tr("I made the Server. \nAnd Wait the Client Connection \n"));
    qDebug("I made the Server. \nAnd Wait the Client Connection ");
    RB_View_Endoscope->setChecked(1);//select endoscopic view as a default
    slotSelectView();

    cB_LeftTool->insertItem("Dissector"); 
    cB_LeftTool->insertItem("Cautery"); 
    cB_LeftTool->insertItem("Grasper"); 
    cB_LeftTool->insertItem("Clip Applier"); 
    cB_LeftTool->insertItem("Scissors"); 

    cB_RightTool->insertItem("Dissector"); 
    cB_RightTool->insertItem("Cautery"); 
    cB_RightTool->insertItem("Grasper"); 
    cB_RightTool->insertItem("Clip Applier"); 
    cB_RightTool->insertItem("Scissors"); 

    UI2Madata.flag01 &= (ALL_ONES - BASIC_LOGIN) ;  //m_logined = FALSE;
    m_surgeon_name = "";
    

    ///// ** Initializing IP Address ** //////////////////////////////////
    if(QFile::exists("./Configuration/IPSetting.inf") )
      m_curr_directory = "./";
    else if(QFile::exists("./GUI_Server/Configuration/IPSetting.inf") )
      m_curr_directory = "./GUI_Server/";
    else if(QFile::exists("../Configuration/IPSetting.inf") )
      m_curr_directory = "../";
    else
      m_curr_directory = "";


    if(m_curr_directory != "" )
    {
      FILE *fp = fopen(m_curr_directory+"Configuration/IPSetting.inf","r");

      //Later, modify using new.. ^^
      QString temp;
      char tmp[100];
      if(fp != NULL)
      {
        fscanf(fp,"%d\n", &m_ip_max_no);
        ipname = new QString[m_ip_max_no];
        ip = new unsigned char[m_ip_max_no][4];
        for(int i=0;i<m_ip_max_no;i++)
        {
          fscanf(fp,"%s %d %d %d %d",tmp,&(ip[i][0]),&(ip[i][1]),&(ip[i][2]),&(ip[i][3]));
          ipname[i]=tmp;
          temp = ipname[i]+" : "+QString("%1.%2.%3.%4").arg(ip[i][0]).arg(ip[i][1]).arg(ip[i][2]).arg(ip[i][3]);
          cB_IP->insertItem(temp); 
        }
      }
      
      QPixmap pm_logo;
      pm_logo.load(m_curr_directory+"Configuration/BioRobotics.bmp");
      logoButton->setPixmap(pm_logo);

      // choose the default ip address
      fscanf(fp,"%s",tmp);
      temp = tmp;
      for (int j=0;j<m_ip_max_no;j++)
      {
		if(QString::compare(ipname[j],temp)==0) 
		{
			cB_IP->setCurrentItem(j);
			UI2Madata.UDPaddr = (ip[j][0]<<24) + (ip[j][1]<<16) + (ip[j][2]<<8) + ip[j][3];
			break;
		}
      }
      fclose(fp);
    }
	else
	{
		cB_IP->insertItem("There is no file");
		UI2Madata.UDPaddr = (192<<24) + (168<<16) + (0<<8) + 100 ; // Buttercup
	}

	//  ** Upload the images of the Stop/Start Buttons ** //
	pm_stop03.load(m_curr_directory+"Pixmaps/Paused.bmp");
	pm_stop02.load(m_curr_directory+"Pixmaps/Operating.bmp");
	pm_stop01.load(m_curr_directory+"Pixmaps/Initializing.bmp");
	pm_stop00.load(m_curr_directory+"Pixmaps/EStop.bmp");
	pm_start.load(m_curr_directory+"Pixmaps/Start.bmp");

	///// ** Connecting signals to slots** //////////////////////
	// button-related slot(function)s
	connect( startButton,		SIGNAL(clicked()),		this, SLOT(slotStart()) );
	connect( okButton,			SIGNAL(clicked()),		this, SLOT(slotClose()) );
	connect( A_startButton,		SIGNAL(clicked()),		this, SLOT(slotStart()) );
	connect( A_okButton,		SIGNAL(clicked()),		this, SLOT(slotClose()) );
	connect( this,				SIGNAL(closeEvent()),	this, SLOT(slotClose()) );
	connect( scaleDecreaseButton, SIGNAL(clicked()),	this, SLOT(slotScaleDecrease()) );
	connect( scaleIncreaseButton, SIGNAL(clicked()),	this, SLOT(slotScaleIncrease()) );
	connect( &m_timer,			SIGNAL(timeout()),		this, SLOT(slotUpdateTimer()) );
	connect( tabWidget,			SIGNAL(currentChanged(QWidget*)), this, SLOT(slotTabChange()) );

	connect(loginButton, SIGNAL(clicked()), this, SLOT(slotCheckLogin()));

	connect(DC_dictateButton,SIGNAL(toggled(bool)),this, SLOT(slotDCDictate(bool)));
	connect(DC_newButton,    SIGNAL( clicked() ),  this, SLOT(slotDCNew()));
	connect(DC_saveButton,   SIGNAL(toggled(bool)),this, SLOT(slotDCStart(bool)));

	connect(RB_View_Endoscope, SIGNAL(clicked()), this, SLOT(slotSelectView()));
	connect( RB_View_OR,       SIGNAL(clicked()), this, SLOT(slotSelectView()));
	connect( RB_View_OR2,      SIGNAL(clicked()), this, SLOT(slotSelectView()));

	connect( cB_IP, SIGNAL(activated(int)), this, SLOT(slotIPChanged(int)) );
	connect( cB_RightTool, SIGNAL(activated(int)), this, SLOT(slotRightToolChanged(int)) );
	connect( cB_LeftTool,  SIGNAL(activated(int)), this, SLOT(slotLeftToolChanged(int)) );
	connect( camAngle1,  SIGNAL(valueChanged(double)), this, SLOT(slotCamAngleChanged()) );
	connect( camAngle2,  SIGNAL(valueChanged(double)), this, SLOT(slotCamAngleChanged()) );
	connect( camAngle3,  SIGNAL(valueChanged(double)), this, SLOT(slotCamAngleChanged()) );
	connect( ITPCheck,  SIGNAL(stateChanged(int)), this, SLOT(slotITPCheckBox(int)) );


	// communication-realted slots
	connect(simServer, SIGNAL(newConnection()), SLOT(slotGUInewConnect()) );
	connect(keypad, SIGNAL(signalAuthorized()), SLOT(slotKeyPadAuthorized()) );
	
	// initialize HTTP connection to log server
	connect(&http,SIGNAL(done(bool)), this, SLOT(slotHttpRead(bool)));
	http.setHost("brl.ee.washington.edu");
}
Esempio n. 18
0
int main(int argc, char** argv)
{
  popen("rm masterFileList.txt 2> /dev/null", "r");
  // Check number of command line args.
  if (argc != 2)
  {
    fprintf( stderr
           , "usage : %s <listening port>\n"
           , argv[0]
           );
    exit(-1);
  }

  // Prepare address struct.
  struct sockaddr_in selfAddr;
  int    port = atoi(argv[1]);

  bzero(&selfAddr, sizeof(selfAddr));
  selfAddr.sin_family = AF_INET;
  selfAddr.sin_addr.s_addr = INADDR_ANY;
  selfAddr.sin_port = htons(port);

  // Create listening socket.
  int lsock;
  if((lsock = socket(AF_INET, SOCK_STREAM,0)) < 0)
  {
    fprintf(stderr, "%s: Cannot open socket.\n", argv[0]);
    exit(-1);
  }

  // Use a non-blocking socket.
  if(fcntl(lsock, F_SETFL, fcntl(lsock, F_GETFL) | O_NONBLOCK) < 0)
  {
    close(lsock);
    fprintf(stderr, "%s: Cannot set scoket to non-blocking.\n", argv[0]);
    exit(-1);      
  }

  // Bind listening socket.
  if(bind( lsock
         , (struct sockaddr*) &(selfAddr)
         , sizeof(selfAddr)
         ) < 0)
  {
    fprintf(stderr, "%s: Could not bind socket to port %d.\n", argv[0], port);
    close(lsock);
    exit(-1);
  }

  // Listen.
  if(listen(lsock, MAX_LISTEN_QUEUE) < 0)
  {
    fprintf( stderr
           , "%s: Failed to listen on port %d.\n"
           , argv[0]
           , port
           );
    close(lsock);
    exit(-1);
  }
  printf("Server listening on port %d.\n", port);
  extern int         errno;
  int                errRecv;
  int                tempSock;
  int                nbytes;
  struct Connection* prev;
  struct Connection* temp;
  struct Connection* head    = newConnection();
  socklen_t          addrLen = sizeof(selfAddr);
  char               buffer[4096];
  FILE*              masterfd;

  while(1)
  {
    bzero(buffer, sizeof(buffer));
    // Accept incoming TCP connections.
    tempSock = accept(lsock, (struct sockaddr*) &selfAddr, &addrLen);
    if(tempSock >= 0)
    {
      temp = head;
      while(temp->next != NULL)
      {
        temp = temp->next;
      }
      temp->sock = tempSock;
      temp->next = newConnection();
    }
    else if(head->sock != -1)
    {
      temp = head;
      prev = NULL;
      do
      {
        bzero(buffer, sizeof(buffer));

        nbytes = recv(temp->sock, buffer, sizeof(buffer), MSG_DONTWAIT);
        errRecv = errno;
        if (nbytes > 0)
        {
          fprintf(stdout, "Message from client: %s\n", buffer);
        }
        else
        {
          if(errRecv != EAGAIN && errRecv != EWOULDBLOCK)
          {
            close(temp->sock);
            if(prev == NULL)
              head = temp->next;
            else
              prev->next = temp->next;
            free(temp);
            continue;
          }
          prev = temp;
          temp = temp->next;
          continue;
        }
        // Handling "ls" client
        if (!strncmp(buffer, "ls", strlen("ls")))
        {
          bzero(buffer,sizeof(buffer));
          masterfd = fopen("masterFileList.txt", "r");
          strcpy(buffer, "MASTER LIST\n");
          if(masterfd != NULL)
          {
            fread(buffer + strlen(buffer), 4096, 1, masterfd); 
            fclose(masterfd);
          } 
          printf("buffer:\n%s", buffer);
          send(temp->sock, buffer, strlen(buffer), 0);
        }
        // Handling client name
        else if (!strncmp(buffer, "IS NAME IN USE:", strlen("IS NAME IN USE:")))
        {
          // Accept/Reject function that checks to make sure client isn't already in list
          send(temp->sock, "CONNECTION ACCEPTED", 20, 0);
        }
        // Handling new file list from client
        else if (!strncmp(buffer, "CLIENT FILES", strlen("CLIENT FILES")))
        {
          addMaster("masterFileList.txt", buffer + strlen("CLIENT FILES\n"));
        }
        // Handling a client exit
        else if (!strncmp(buffer, "Client exit, please remove:", strlen("Client exit, please remove:")))
        {
          printf("%s\n", buffer);
          close(temp->sock);
          if(prev == NULL)
          {
            if(temp->next != NULL)
              head = temp->next;
            else
              head->sock = -1;
          }
          else
          {
            prev->next = temp->next;
          }
          free(temp);
          delMaster("masterFileList.txt", buffer + strlen("Client exit, please remove:"));
          break;
        }
        // If command is unknown
        else 
        { 
          send(temp->sock, "Command is not recognized.\n", 96, 0); 
        }   
        prev = temp;
        temp = temp->next;
      } while(temp != NULL && temp->next != NULL);
    }
    else
    {
      continue;
    }
  }
}
Server::Server(QWidget *parent)
    : QDialog(parent)
{
    statusLabel = new QLabel;
    quitButton = new QPushButton(tr("Quit"));
    quitButton->setAutoDefault(false);

//! [0] //! [1]
    tcpServer = new QTcpServer(this);
    if (!tcpServer->listen()) {
        QMessageBox::critical(this, tr("Fortune Server"),
                              tr("Unable to start the server: %1.")
                              .arg(tcpServer->errorString()));
        close();
        return;
    }
//! [0]
    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
    statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
                            "Run the Fortune Client example now.")
                         .arg(ipAddress).arg(tcpServer->serverPort()));
//! [1]

//! [2]
    fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
             << tr("You've got to think about tomorrow.")
             << tr("You will be surprised by a loud noise.")
             << tr("You will feel hungry again in another hour.")
             << tr("You might have mail.")
             << tr("You cannot kill time without injuring eternity.")
             << tr("Computers are not intelligent. They only think they are.");
//! [2]

    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
//! [3]
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune()));
//! [3]

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addStretch(1);
    buttonLayout->addWidget(quitButton);
    buttonLayout->addStretch(1);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(statusLabel);
    mainLayout->addLayout(buttonLayout);
    setLayout(mainLayout);

    setWindowTitle(tr("Fortune Server"));
}
Esempio n. 20
0
//! ----------------------------------------------------------------------------------------------
//!
//! \brief igtCommunicationStack::receptConnection
//! \param remoteIP
//!
void igtCommunicationStack::receptConnection(QString remoteIP){
    QString ret = remoteIP;
    emit newConnection(ret);
}
Esempio n. 21
0
void QXmppSocksServer::slotReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (!socket || !m_states.contains(socket))
        return;

    if (m_states.value(socket) == ConnectState)
    {
        // receive connect to server request
        QByteArray buffer = socket->readAll();
        if (buffer.size() < 3 ||
            buffer.at(0) != SocksVersion ||
            buffer.at(1) + 2 != buffer.size())
        {
            qWarning("QXmppSocksServer received invalid handshake");
            socket->close();
            return;
        }

        // check authentication method
        bool foundMethod = false;
        for (int i = 2; i < buffer.size(); i++)
        {
            if (buffer.at(i) == NoAuthentication)
            {
                foundMethod = true;
                break;
            }
        }
        if (!foundMethod)
        {
            qWarning("QXmppSocksServer received bad authentication method");

            buffer.resize(2);
            buffer[0] = SocksVersion;
            buffer[1] = static_cast<unsigned char>(NoAcceptableMethod);
            socket->write(buffer);

            socket->close();
            return;
        }

        // advance state
        m_states.insert(socket, CommandState);

        // send connect to server response
        buffer.resize(2);
        buffer[0] = SocksVersion;
        buffer[1] = NoAuthentication;
        socket->write(buffer);

    } else if (m_states.value(socket) == CommandState) {
        // disconnect from signals
        disconnect(socket, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));

        // receive command
        QByteArray buffer = socket->read(3);
        if (buffer.size() != 3 ||
            buffer.at(0) != SocksVersion ||
            buffer.at(1) != ConnectCommand ||
            buffer.at(2) != 0x00)
        {
            qWarning("QXmppSocksServer received an invalid command");
            socket->close();
            return;
        }

        // parse host
        quint8 hostType;
        QByteArray hostName;
        quint16 hostPort;
        QDataStream stream(socket);
        if (!parseHostAndPort(stream, hostType, hostName, hostPort))
        {
            qWarning("QXmppSocksServer could not parse type/host/port");
            socket->close();
            return;
        }

        // notify of connection
        m_states.insert(socket, ReadyState);
        emit newConnection(socket, hostName, hostPort);

        // send response
        buffer.resize(3);
        buffer[0] = SocksVersion;
        buffer[1] = Succeeded;
        buffer[2] = 0x00;
        buffer.append(encodeHostAndPort(
            DomainName,
            hostName,
            hostPort));
        socket->write(buffer);
    }
}
Esempio n. 22
0
IntProcServer::IntProcServer()
{
    clientConnection=NULL;
    connect(this, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));
}
Esempio n. 23
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_server(new NetworkServer(this)),
    m_ipList(),
    m_bgm(this)
{
    ui->setupUi(this);
    m_bgm.setMedia(QUrl::fromLocalFile("./Music/thestonemasons.wav"));
    m_bgm.setVolume(50);
    m_bgm.play();
    connect(&m_bgm, SIGNAL(stateChanged(QMediaPlayer::State)), &m_bgm, SLOT(play()));
    setFixedSize(width(), height());
    m_gobang = new Gobang(this);
    m_startMenu = new StartMenu(this);
    m_waitWidget = new waitWidget(this);
    setCursor(QCursor(QPixmap(":/Pic/arrows.png"), 1, 1));
    m_gobang->hide();
    m_waitWidget->hide();
    m_startMenu->show();
    currentWidget = m_startMenu;
    m_server->listen();
    m_server->getIP();
    m_waitWidget->ui->ipLabel->setText("您的IP是:" + m_server->Sadress);
    m_timer.setInterval(1000);
    currentState = m_server->readWriteSocket->state();
    m_time1.setInterval(200); m_time1.start();
    connect(&m_time1, SIGNAL(timeout()), this, SLOT(checkState()));
    m_timer.start();
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(checkUnactive()));

    connect(m_startMenu->ui->startServer, SIGNAL(clicked()), this, SLOT(setWaiting()));
    connect(m_startMenu->ui->startServer, SIGNAL(clicked()), m_gobang, SLOT(setHost()));
    connect(m_startMenu->ui->startServer, SIGNAL(clicked()), m_server, SLOT(closeListen()));
    connect(m_startMenu->ui->startServer, SIGNAL(clicked()), m_server, SLOT(initServer()));

    connect(m_startMenu->ui->startClient, SIGNAL(clicked()), this, SLOT(connectHost()));
    connect(m_startMenu->ui->startClient, SIGNAL(clicked()), m_server, SLOT(closeListen()));

    connect(m_waitWidget->ui->ok, SIGNAL(clicked()), this, SLOT(broadcast()));
    connect(m_waitWidget->ui->ok, SIGNAL(clicked()), m_waitWidget->ui->setBox, SLOT(hide()));
    connect(m_waitWidget->ui->ok, SIGNAL(clicked()), m_waitWidget->ui->waitLabel, SLOT(show()));
    connect(m_waitWidget->ui->back, SIGNAL(clicked()), m_server, SLOT(closeWrite()));
    connect(m_waitWidget->ui->back, SIGNAL(clicked()), m_server, SLOT(listen()));
    connect(m_waitWidget->ui->back, SIGNAL(clicked()), this, SLOT(setStart()));

    connect(m_gobang, SIGNAL(sendSignal(int, Step)), m_server, SLOT(sendMessage(int, Step)));

    connect(m_server, SIGNAL(setPieces(Step)), m_gobang, SLOT(setPieces(const Step&)));
    connect(m_server, SIGNAL(findPlayer(QString)), this, SLOT(findPlayer(QString)));
    connect(m_server, SIGNAL(changeCamp(int)), m_gobang, SLOT(changeCamp(int)));
    connect(m_server, SIGNAL(recall(int)), m_gobang, SLOT(recallDone(int)));
    connect(m_server, SIGNAL(reStart()), m_gobang, SLOT(reStart()));
    connect(m_server, SIGNAL(agreeRecall()), m_gobang, SLOT(on_recall()));
    connect(m_server, SIGNAL(askForRecall()), m_gobang, SLOT(forRecall()));
    connect(m_server, SIGNAL(agreeExit()), this, SLOT(setStart()));
    connect(m_server, SIGNAL(agreeExit()), m_gobang, SLOT(on_exit()));
    connect(m_server, SIGNAL(refuse()), m_gobang, SLOT(on_refuse()));
    connect(m_server, SIGNAL(agreeExit()), m_server, SLOT(listen()));
    connect(m_server, SIGNAL(askForExit()), m_gobang, SLOT(forExit()));
    connect(m_server, SIGNAL(changeState(int, int, int)), m_gobang, SLOT(changeCurrentState(int, int, int)));
    connect(m_server->listenSocket, SIGNAL(newConnection()), this, SLOT(setGobang()));
    connect(m_server->listenSocket, SIGNAL(newConnection()), m_server, SLOT(closeWrite()));
    connect(m_server->listenSocket, SIGNAL(newConnection()), m_server, SLOT(closeListen()));

}
Esempio n. 24
0
SensingServer::SensingServer(QObject *parent) :
	QTcpServer(parent)
{
	connect(this, SIGNAL(newConnection()), this, SLOT(newClient()));
}
Esempio n. 25
0
HttpServer::HttpServer(QObject *parent)
    : QObject(parent)
    , _server(new QTcpServer(this))
{
    this->connect(this->_server, SIGNAL(newConnection()), SLOT(_onNewConnection()));
}
Esempio n. 26
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
//    setCentralWidget(ui->tabWidget);
    //设置编码,可用于国际化
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf-8"));

    //此定时器为轮询串口缓存数据
    serial_read_fresh_t=new QTimer(this);
    //设置定时器刷新周期
    serial_read_fresh_t->setInterval(400);
    //对串口进行初始化
    if(ser_serial_port_init()==Utils::SUCCESS)
    {
        ui->infoPad->append("Ser : Found Serial Device");
        th.start();
    }
    else
    {
        ui->infoPad->append(("Ser : No Serial Device Found"));
    }
    //初始化tcp服务器端
    tcpServer =new QTcpServer(this);
    //初始化udp发送套接字对象
    udpSendSocket = new QUdpSocket(this);
    //初始化udp接收套接字对象
    udpReceiveSocket = new QUdpSocket(this);
    //绑定本地udp套接字监听//8904
    udpReceiveSocket->bind(Utils::SER_UDP_RCV_PORT, QUdpSocket::ShareAddress);
    //绑定本地udp套接字的readyRead信号到processPendingDatagrams槽函数
    connect(udpReceiveSocket, SIGNAL(readyRead()),this, SLOT(processPendingDatagrams()));
    //初始化客户端默认地址对象
    addr = new QHostAddress("192.168.1.1");

    //设置按钮的初始化状态
    ui->startBtn->setEnabled(true);
    ui->stopBtn->setEnabled(false);
    //绑定tcpServer的newConnection信号到newConnectionComing槽函数
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnectionComing()));
    //绑定startBtn的clicked信号到listenBtnClicked槽函数
    connect(ui->startBtn,SIGNAL(clicked()),this,SLOT(listenBtnClicked()));
     //绑定stopBtn的clicked信号到listenBtnClicked槽函数
    connect(ui->stopBtn,SIGNAL(clicked()),this,SLOT(stopBtnClicked()));
    //子节点将会发送的命令
    //在下一个迭代版本中将分离出去
    //
    // 将公用数据移入Utils工具类
    //  2014,03,15 已完成

    //温度传感器子节点发送的命令头
    // TEMP ="temp_data_is:";
    //湿度传感器子节点发送的命令头
    // HUMI ="humi_data_is:";

    table_fresh_t=new QTimer(this);
    table_fresh_t->setInterval(1000);
    connect(table_fresh_t,SIGNAL(timeout()),this,SLOT(view_data()));
    table_fresh_t->start();
    //将信号send_cmd_to_node与槽函数sendSerCom绑定
    connect(this,SIGNAL(send_cmd_to_node(QString)),this,SLOT(sendSerCom(QString)));
    //将信号send_data_to_thread与槽函数setData绑定
    connect(this,SIGNAL(send_data_to_thread(QString)),&th,SLOT(setData(QString)));
}
Esempio n. 27
0
BrowserApplication::BrowserApplication(int &argc, char **argv)
    : QApplication(argc, argv)
    , m_localServer(0)
{
    QCoreApplication::setOrganizationName(QLatin1String("Qt"));
    QCoreApplication::setApplicationName(QLatin1String("demobrowser"));
    QCoreApplication::setApplicationVersion(QLatin1String("0.1"));
#ifdef Q_WS_QWS
    // Use a different server name for QWS so we can run an X11
    // browser and a QWS browser in parallel on the same machine for
    // debugging
    QString serverName = QCoreApplication::applicationName() + QLatin1String("_qws");
#else
    QString serverName = QCoreApplication::applicationName();
#endif
    QLocalSocket socket;
    socket.connectToServer(serverName);
    if (socket.waitForConnected(500)) {
        QTextStream stream(&socket);
        QStringList args = QCoreApplication::arguments();
        if (args.count() > 1)
            stream << args.last();
        else
            stream << QString();
        stream.flush();
        socket.waitForBytesWritten();
        return;
    }

#if defined(Q_WS_MAC)
    QApplication::setQuitOnLastWindowClosed(false);
#else
    QApplication::setQuitOnLastWindowClosed(true);
#endif

    m_localServer = new QLocalServer(this);
    connect(m_localServer, SIGNAL(newConnection()),
            this, SLOT(newLocalSocketConnection()));
    if (!m_localServer->listen(serverName)) {
        if (m_localServer->serverError() == QAbstractSocket::AddressInUseError
            && QFile::exists(m_localServer->serverName())) {
            QFile::remove(m_localServer->serverName());
            m_localServer->listen(serverName);
        }
    }

#ifndef QT_NO_OPENSSL
    if (!QSslSocket::supportsSsl()) {
    QMessageBox::information(0, "Demo Browser",
                 "This system does not support OpenSSL. SSL websites will not be available.");
    }
#endif

    QDesktopServices::setUrlHandler(QLatin1String("http"), this, "openUrl");
    QString localSysName = QLocale::system().name();

    installTranslator(QLatin1String("qt_") + localSysName);

    QSettings settings;
    settings.beginGroup(QLatin1String("sessions"));
    m_lastSession = settings.value(QLatin1String("lastSession")).toByteArray();
    settings.endGroup();

#if defined(Q_WS_MAC)
    connect(this, SIGNAL(lastWindowClosed()),
            this, SLOT(lastWindowClosed()));
#endif

    QTimer::singleShot(0, this, SLOT(postLaunch()));
}
Esempio n. 28
0
void QwuiTcpServer::incomingConnection(int socketDescriptor)
{
    emit newConnection(socketDescriptor);
}
Esempio n. 29
0
O2ReplyServer::O2ReplyServer(QObject *parent): QTcpServer(parent),
  timeout_(15), maxtries_(3), tries_(0) {
    qDebug() << "O2ReplyServer: Starting";
    connect(this, SIGNAL(newConnection()), this, SLOT(onIncomingConnection()));
    replyContent_ = "<HTML></HTML>";
}
Esempio n. 30
0
void PrivTcpServer::incomingConnection(int socket)
{
    emit newConnection(socket);
}