bool SocketIOClient::connect(char thehostname[], int theport) {
	if (!client.connect(thehostname, theport)) return false;
	hostname = thehostname;
	port = theport;
	sendHandshake(hostname);
	return readHandshake();
}
Exemplo n.º 2
0
void
AsyncCDDBPLookup::doHandshake()
{
    sendHandshake();

    state_ = WaitingForHandshake;
}
bool WebSocketClient::connect() {
    if (_client.connect(_server, _port)) {
        sendHandshake();
        return readHandshake();
    }
    return false;
}
Exemplo n.º 4
0
bool Nimbits::connectSocket(String points[], int count) {
    bool result = false;

    char path[256];
    path[0] = '\0';
    byte uuidNumber[16];
    String pointJson = arrayToJson(points, count);



     strcat(path, "/socket?token=");
     strcat(path, _authToken.c_str());
     if (count > 0) {
        strcat(path, "&points=");
        strcat(path, pointJson.c_str());
     }



    if (ethernetClient.connect(_hostname.c_str(), _port)) {
        sendHandshake(path);
        result = readHandshake();
    }
    
	return result;
}
Exemplo n.º 5
0
bool XSocketClient::connect(char hostname[], int port) {
	bool result = false;
	if (_client.connect(hostname, port)) {
		sendHandshake();
		result = readHandshake();
	}
	return result;
}
bool WebSocketClient::connect() {
    bool result = false;
    if (_client.connect()) {
        sendHandshake();
        result = readHandshake();
    }
    
	return result;
}
bool SocketIOClient::connect(unsigned int id, char thehostname[], int theport) {
	ID = id;
	if (!client.connect(thehostname, theport)) return false;
	hostname = thehostname;
	port = theport;
	sendHandshake(hostname);
	bool ret = readHandshake();
	socketHandshake();
	return ret;
}
Exemplo n.º 8
0
void AmpacheListEngine::run()
{
    QThread::setTerminationEnabled(true);
    m_stop = false;

    if (m_updateSourceInfo || m_removeSourceInfo) {
        return;
    }


    //Create media list based on engine argument and filter
    QList<MediaItem> mediaList;

    QString engineArg = m_mediaListProperties.engineArg();
    QStringList engineFilterList = m_mediaListProperties.engineFilterList();

    if (!engineFilterList.isEmpty()) {
        QString server = m_mediaListProperties.filterFieldValue("server");
        QString request = m_mediaListProperties.filterFieldValue("request");
        m_pendingRequest["server"] = server;
        m_pendingRequest["request"] = request;

        if (request == "root") {
            QString username = m_mediaListProperties.filterFieldValue("username");
            QString key = m_mediaListProperties.filterFieldValue("key");

            //Handshake
            m_pendingRequest["username"] = username;
            m_pendingRequest["key"] = key;
            sendHandshake(server, username, key);

        } else {
            QString requestUrlStr = server + m_mediaListProperties.filterFieldValue("requestPath");
            KUrl requestUrl(requestUrlStr);
            if (!requestUrl.isEmpty()) {
                QString targetFile = QString("bangarang/temp/%1").arg(QString("ampacheResult-%1-%2").arg(m_requestSignature, m_subRequestSignature));
                KUrl targetUrl = KUrl(KStandardDirs::locateLocal("data", targetFile, true));
                connectDownloader();
                emit download(requestUrl, targetUrl);
            }
        }

        //Start event loop to wait for feed results
        exec();
    } else {
        //Return no results
        m_mediaListProperties.summary = i18np("1 item", "%1 items", mediaList.count());
        m_mediaListProperties.type = QString("Categories");
        emit results(m_requestSignature, mediaList, m_mediaListProperties, true, m_subRequestSignature);
    }

}
Exemplo n.º 9
0
inline void OmniApp::start() {
	if (mOmni.activeStereo()) {
		Window::displayMode(Window::displayMode() | Window::STEREO_BUF);
	}
	
	create();
	
	if (mOmni.fullScreen()) {
		fullScreen(true);
		cursorHide(true);
	}
	
	if (!bSlave) { 
		if(oscSend().opened()) sendHandshake();
		mAudioIO.start();
	}
	
	Main::get().start();
}
Exemplo n.º 10
0
    // check if a target is connected, and attempt to connect if not
    bool 
    VASTnet::validateConnection (id_t host_id)
    {
        // if it's message to self or already connected
        if (_manager->getID () == host_id || _manager->isConnected (host_id) == true)
            return true;

        // resolve address of host
        std::map<id_t, Addr>::iterator it = _id2addr.find (host_id);
        if (it == _id2addr.end ())
            return false;

        IPaddr &remote_addr = it->second.publicIP;

        // otherwise try to initiate connection & send handshake message
        if (_manager->connect (host_id, remote_addr.host, remote_addr.port) == false)
            return false;
        
        sendHandshake (host_id);

        return true;
    }
//--------------------------------------------------------------
void ofxMatrixNetworkServer::update() {
    //for each client lets send them a message letting them know what port they are connected on
	for(int i = 0; i < getLastID(); i++){
		if(isClientConnected(i)){
            //if we don't have a string allocated yet: lets create one
            //if(i >= storeText.size() ){
            //    storeText.push_back( string() );
            //}
            
            //if we don't have a string allocated yet: lets create one
            if(i >= tx_valid.size() ){
                tx_valid.push_back(0);
            }
            
            //we only want to update the text we have recieved there is data
            string str = receive(i);
            
            if(str == "handshake"){
                ofLog(OF_LOG_NOTICE, "handshake with client " + ofToString(i));
                sendHandshake(i);
                tx_valid[i] = 1;
            }else if(str.find_first_of("nextframe") != -1){
                //ofLog(OF_LOG_NOTICE, "nextframe for client " + ofToString(i) + " - " + str);
                tx_valid[i] = 2;
            }else if(str == "disconnect"){
                ofLog(OF_LOG_NOTICE, "disconnect client " + ofToString(i));
                sendDisconnect(i);
                disconnectClient(i);
                tx_valid[i] = 0;
            }
            
            //if(str.length() > 0){
            //    storeText[i] = str;
            //}
        }else{
            tx_valid[i] = 0;
        }
	}
}
Exemplo n.º 12
0
void handleCloseHandshake()
{

	if (recvHandshake() == MODE_COMPLETE)
		sendHandshake(MODE_COMPLETE);
}
Exemplo n.º 13
0
int startConnection(int port)
{

	if (SendSocket != INVALID_SOCKET || RecvSocket != INVALID_SOCKET)
	{
		return 0;
	}

	WSADATA wsaData;
	int iResult;

	//----------------------
	// Initialize Winsock
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != NO_ERROR) {
		printf("WSAStartup failed with error: %d\n", iResult);
		return 0;
	}

	//---------------------------------------------
	// Create a socket for sending data
	SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (SendSocket == INVALID_SOCKET) {
		printf("socket failed with error: %ld\n", WSAGetLastError());
		closeConnection();
		return 0;
	}

	//---------------------------------------------
	// Create a socket for recving data
	RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (SendSocket == INVALID_SOCKET) {
		printf("socket failed with error: %ld\n", WSAGetLastError());
		closeConnection();
		return 0;
	}
	//-----------------------------------------------
    // Bind the socket to any address and the specified port.
    SendAddr.sin_family = AF_INET;
    SendAddr.sin_port = htons(port);
    SendAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    iResult = bind(RecvSocket, (SOCKADDR *) & SendAddr, sizeof (SendAddr));
    if (iResult != 0) {
        wprintf(L"bind failed with error %d\n", WSAGetLastError());
		closeConnection();
        return 0;
    }

	//---------------------------------------------
	// Set up the RecvAddr structure with the IP address of
	// the receiver
	RecvAddr.sin_family = AF_INET;
	RecvAddr.sin_port = htons(port+1);

	if (recvHandshake() != MODE_READY)
	{

		printf("Sender not ready");
		closeConnection();
		return 0;

	}

	sendHandshake(MODE_READY);

	// set receive timeout to 1
	if (!setTimeout(RecvSocket,-1))
	{

		closeConnection();
		return 0;

	}

	return 1;

}
Exemplo n.º 14
0
void GroupClient::retrieveData(GroupSocket *const /* socket */,
                               const Messages message,
                               const QVariantMap &data)
{
    if (message == Messages::STATE_KICKED) {
        emit messageBox(QString("You got kicked! Reason: %1").arg(data["text"].toString()));
        stop();
        return;
    }
    if (socket.getProtocolState() == ProtocolState::AwaitingLogin) {
        // Login state. either REQ_HANDSHAKE, REQ_LOGIN, or ACK should come
        if (message == Messages::REQ_HANDSHAKE) {
            sendHandshake(data);
        } else if (message == Messages::REQ_LOGIN) {
            assert(!NO_OPEN_SSL);
            socket.setProtocolVersion(proposedProtocolVersion);
            socket.startClientEncrypted();
        } else if (message == Messages::ACK) {
            // aha! logged on!
            sendMessage(&socket, Messages::REQ_INFO);
            socket.setProtocolState(ProtocolState::AwaitingInfo);
        } else {
            // ERROR: unexpected message marker!
            // try to ignore?
            qWarning("(AwaitingLogin) Unexpected message marker. Trying to ignore.");
        }

    } else if (socket.getProtocolState() == ProtocolState::AwaitingInfo) {
        // almost connected. awaiting full information about the connection
        if (message == Messages::UPDATE_CHAR) {
            emit scheduleAction(new AddCharacter(data));
        } else if (message == Messages::STATE_LOGGED) {
            socket.setProtocolState(ProtocolState::Logged);
        } else if (message == Messages::REQ_ACK) {
            sendMessage(&socket, Messages::ACK);
        } else {
            // ERROR: unexpected message marker!
            // try to ignore?
            qWarning("(AwaitingInfo) Unexpected message marker. Trying to ignore.");
        }

    } else if (socket.getProtocolState() == ProtocolState::Logged) {
        if (message == Messages::ADD_CHAR) {
            emit scheduleAction(new AddCharacter(data));
        } else if (message == Messages::REMOVE_CHAR) {
            emit scheduleAction(new RemoveCharacter(data));
        } else if (message == Messages::UPDATE_CHAR) {
            emit scheduleAction(new UpdateCharacter(data));
        } else if (message == Messages::RENAME_CHAR) {
            emit scheduleAction(new RenameCharacter(data));
        } else if (message == Messages::GTELL) {
            emit gTellArrived(data);
        } else if (message == Messages::REQ_ACK) {
            sendMessage(&socket, Messages::ACK);
        } else {
            // ERROR: unexpected message marker!
            // try to ignore?
            qWarning("(Logged) Unexpected message marker. Trying to ignore.");
        }
    }
}
Exemplo n.º 15
0
void *handleClient(void *args) {
	pthread_detach(pthread_self());
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
	pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
	pthread_cleanup_push(&cleanup_client, args);

	int buffer_length = 0, string_length = 1, reads = 1;

	ws_client *n = args;
	n->thread_id = pthread_self();

	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

	char buffer[BUFFERSIZE];
	n->string = (char *) malloc(sizeof(char));

	if (n->string == NULL) {
		pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
		handshake_error("Couldn't allocate memory.", ERROR_INTERNAL, n);
		pthread_exit((void *) EXIT_FAILURE);
	}

	printf("Client connected with the following information:\n"
		   "\tSocket: %d\n"
		   "\tAddress: %s\n\n", n->socket_id, (char *) n->client_ip);
	printf("Checking whether client is valid ...\n\n");
	fflush(stdout);

	/**
	 * Getting headers and doing reallocation if headers is bigger than our
	 * allocated memory.
	 */
	do {
		memset(buffer, '\0', BUFFERSIZE);
		if ((buffer_length = recv(n->socket_id, buffer, BUFFERSIZE, 0)) <= 0){
			pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
			handshake_error("Didn't receive any headers from the client.", 
					ERROR_BAD, n);
			pthread_exit((void *) EXIT_FAILURE);
		}

		if (reads == 1 && strlen(buffer) < 14) {
			handshake_error("SSL request is not supported yet.", 
					ERROR_NOT_IMPL, n);
			pthread_exit((void *) EXIT_FAILURE);
		}

		string_length += buffer_length;

		char *tmp = realloc(n->string, string_length);
		if (tmp == NULL) {
			pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
			handshake_error("Couldn't reallocate memory.", ERROR_INTERNAL, n);
			pthread_exit((void *) EXIT_FAILURE);
		}
		n->string = tmp;
		tmp = NULL;

		memset(n->string + (string_length-buffer_length-1), '\0', 
				buffer_length+1);
		memcpy(n->string + (string_length-buffer_length-1), buffer, 
				buffer_length);
		reads++;
	} while( strncmp("\r\n\r\n", n->string + (string_length-5), 4) != 0 
			&& strncmp("\n\n", n->string + (string_length-3), 2) != 0
			&& strncmp("\r\n\r\n", n->string + (string_length-8-5), 4) != 0
			&& strncmp("\n\n", n->string + (string_length-8-3), 2) != 0 );
	
	printf("User connected with the following headers:\n%s\n\n", n->string);
	fflush(stdout);

	ws_header *h = header_new();

	if (h == NULL) {
		pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
		handshake_error("Couldn't allocate memory.", ERROR_INTERNAL, n);
		pthread_exit((void *) EXIT_FAILURE);
	}

	n->headers = h;

	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
	if ( parseHeaders(n->string, n, port) < 0 ) {
		pthread_exit((void *) EXIT_FAILURE);
	}

	if ( sendHandshake(n) < 0 && n->headers->type != UNKNOWN ) {
		pthread_exit((void *) EXIT_FAILURE);	
	}	

	list_add(l, n);
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

	printf("Client has been validated and is now connected\n\n");
	printf("> ");
	fflush(stdout);

	uint64_t next_len = 0;
	char next[BUFFERSIZE];
	memset(next, '\0', BUFFERSIZE);

	while (1) {
		if ( communicate(n, next, next_len) != CONTINUE) {
			break;
		}

		pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
		if (n->headers->protocol == CHAT) {
			list_multicast(l, n);
		} else if (n->headers->protocol == ECHO) {
			list_multicast_one(l, n, n->message);
		} else {
			list_multicast_one(l, n, n->message);
		}
		pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

		if (n->message != NULL) {
			memset(next, '\0', BUFFERSIZE);
			memcpy(next, n->message->next, n->message->next_len);
			next_len = n->message->next_len;
			message_free(n->message);
			free(n->message);
			n->message = NULL;	
		}
	}
	
	printf("Shutting client down..\n\n");
	printf("> ");
	fflush(stdout);

	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
	list_remove(l, n);
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

	pthread_cleanup_pop(0);
	pthread_exit((void *) EXIT_SUCCESS);
}
Exemplo n.º 16
0
		ConnectionState Connection::update(double time)
		{
			// if CLOSED or CONNECTED, nothing happens
			// if CONNECTING or HANDSHAKING, incomming packets are proccessed for update
			Address sender;
			int size;

			switch(state) {
			case CONNECTING:
				// accept only connectionResponse (and get its connectionId)
				while (size = socket.receive(sender,buffer, NSL_MAX_UDP_PACKET_SIZE)) {
					if (size != 6) {
						continue;
					}

					// reset buffer stream
					bufferStream->resetStream(size);
					if (bufferStream->read<uint16>() != applicationId) {
						continue;
					}
					connectionId = bufferStream->read<int32>();
					state = HANDSHAKING;
					sendHandshake(time);
					return state;
				}
				
				if (lastRequest + NSL_TIMEOUT_CLIENT_CONNECTION_REQUEST < time) {
					sendConnectionRequest(time);
				}
				break;
			case HANDSHAKING:
				// accept only handshakeResponse (and get its status)
				while (size = socket.receive(sender,buffer,NSL_MAX_UDP_PACKET_SIZE)) {
					if (size < 7) {
						continue;
					}

					// reset buffer stream
					bufferStream->resetStream(size);
					if (bufferStream->read<uint16>() != applicationId) {
						continue;
					}
					if (bufferStream->read<uint32>() != connectionId) {
						continue;
					}

					// process handshake response
					switch (bufferStream->readByte()) {
					case NSL_CONNECTION_FLAG_DISCONNECT:
						state = CLOSED;
						return state;
					case NSL_CONNECTION_FLAG_UPDATE:
						state = CONNECTED;
						bufferedMessage = bufferStream->createSubreader(size - 7, true);
						return state;
					case NSL_CONNECTION_FLAG_COMPRESSED_UPDATE:
						state = CONNECTED;
#ifdef NSL_COMPRESS
						bufferedMessage = decompressStream(bufferStream);
#else
						throw Exception(NSL_EXCEPTION_LIBRARY_ERROR, "NSL: Compressed update was received from server, but compression is turned of on client");
#endif
						return state;
					default:
						throw Exception(NSL_EXCEPTION_LIBRARY_ERROR, "NSL: protocol error, received not expected data.");
					}
				}

				if (lastRequest + NSL_TIMEOUT_CLIENT_HANDSHAKE < time) {
					sendHandshake(time);
				}
				break;
			case CLOSED:
				// throw away all incomming packets so they will not mess later
				while (size = socket.receive(sender,buffer,NSL_MAX_UDP_PACKET_SIZE)) {}
			default:
				break;
			}

			return state;
		}