コード例 #1
0
ファイル: duktoprotocol.cpp プロジェクト: Stankim/dukto
void DuktoProtocol::handleMessage(QByteArray &data, QHostAddress &sender)
{
    char msgtype = data.at(0);

    switch(msgtype)
    {
        case 0x01:  // HELLO (broadcast)
        case 0x02:  // HELLO (unicast)
            data.remove(0, 1);
            if (data != getSystemSignature()) {
                mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), DEFAULT_UDP_PORT);
                if (msgtype == 0x01) sayHello(sender, DEFAULT_UDP_PORT);
                emit peerListAdded(mPeers[sender.toString()]);
            }
            break;

        case 0x03:  // GOODBYE
            emit peerListRemoved(mPeers[sender.toString()]);
            mPeers.remove(sender.toString());
            break;

        case 0x04:  // HELLO (broadcast) with PORT
        case 0x05:  // HELLO (unicast) with PORT
            data.remove(0, 1);
            qint16 port = *((qint16*) data.constData());
            data.remove(0, 2);
            if (data != getSystemSignature()) {
                mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), port);
                if (msgtype == 0x04) sayHello(sender, port);
                emit peerListAdded(mPeers[sender.toString()]);
            }
            break;
    }

}
コード例 #2
0
ファイル: duktoprotocol.cpp プロジェクト: arthurzam/dukto-qt5
void DuktoProtocol::handleMessage(QByteArray &data, QHostAddress &sender)
{
    char msgtype = data.at(0);

    switch(msgtype)
    {
    case MSG_HELLO_BROADCAST:
    case MSG_HELLO_UNICAST:
        data.remove(0, 1);
        if (data != getSystemSignature()) {
            mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), DEFAULT_UDP_PORT);
            if (msgtype == MSG_HELLO_BROADCAST) sayHello(sender, DEFAULT_UDP_PORT);
            emit peerListAdded(mPeers[sender.toString()]);
        }
        break;

    case MSG_GOODBYE:
        emit peerListRemoved(mPeers[sender.toString()]);
        mPeers.remove(sender.toString());
        break;

    case MSG_HELLO_PORT_BROADCAST:
    case MSG_HELLO_PORT_UNICAST:
        data.remove(0, 1);
        qint16 port = *((qint16*) data.constData());
        data.remove(0, 2);
        if (data != getSystemSignature()) {
            mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), port);
            if (msgtype == MSG_HELLO_PORT_BROADCAST) sayHello(sender, port);
            emit peerListAdded(mPeers[sender.toString()]);
        }
        break;
    }

}
コード例 #3
0
ファイル: server_1.cpp プロジェクト: orcchg/CppCourse
// ----------------------------------------------
void PeerServer::run() {
    linger linger_opt = { 1, 0 };  // Linger active, timeout 0
    setsockopt(m_socket, SOL_SOCKET, SO_LINGER, &linger_opt, sizeof(linger_opt));

    listen(m_socket, 20);

    while (true) {  // server loop
        sockaddr_in client_address_structure;
        socklen_t client_address_structure_size = sizeof(client_address_structure);

        // accept one pending connection, waits until a new connection comes
        int data_transfer_socket = accept(m_socket, reinterpret_cast<sockaddr*>(&client_address_structure), &client_address_structure_size);
        if (data_transfer_socket < 0) {
            ERR("Failed to open new socket for data transfer");
            continue;  // skip failed connection
        }

        // get incoming client
        printClientInfo(client_address_structure);
        char buf[32];
        recv(data_transfer_socket, buf, 32, 0);
        std::string input_str = std::string(buf);
        int delimiter_index = input_str.find_first_of("#");
        int client_id = std::atoi(input_str.substr(0, delimiter_index).c_str());
        int dest_client_id = std::atoi(input_str.substr(delimiter_index + 1).c_str());
        m_clients_map[client_id] = Peer(dest_client_id, data_transfer_socket);
        INF("Client [id = %i] has connected, destination client id: %i", client_id, dest_client_id);

        // send confirmation to client
        std::string hello_message = "Server: connection has been established\n\0";
        send(data_transfer_socket, hello_message.c_str(), hello_message.length(), 0);

        handleClientMessages(client_id, data_transfer_socket);  // start single thread to handle incoming data
    }
}
コード例 #4
0
Peer* Framework::resolveHost(const std::string& hostname)
{
	IPaddress ip;
	if (NET2_ResolveHost(&ip, (char*)hostname.c_str(), sendport) != -1)
	{
		peer.push_back(Peer(ip.host));
		std::cout << "Server resolved at " << peer.back().hostname << std::endl;
		return &(peer.back());
	} else return NULL;
}
コード例 #5
0
Peer* Framework::getCreatePeer(unsigned int host)
{
	for (int i = 0; i < peer.size(); i++)
		if (peer[i].host == host)
			return &peer[i];

	peer.push_back(Peer(host));
	std::cout << "Peer connected from " << peer.back().hostname << std::endl;
	return &(peer.back());
}
コード例 #6
0
ファイル: P2P_connection.cpp プロジェクト: ulianast/KraTor
	SOCKET P2P_connection::AcceptNewConnection()
	{
		SOCKET sNewConnection=TCP_connection::AcceptNewConnection();
		if(sNewConnection!=INVALID_SOCKET)
		{
			Peer pNewPeer=Peer();
			pNewPeer.sSocket=sNewConnection;
			mPeers[sNewConnection]=&pNewPeer;
		}
		return sNewConnection;
	}
コード例 #7
0
Telegram::Peer Telegram::Peer::fromString(const QString &string)
{
    // Possible schemes: user1234, chat1234, channel1234
    if (string.length() < 5) {
        return Peer();
    }
    bool ok = true;
    switch (string.at(0).toLatin1()) {
    case 'u': // user
        if (string.startsWith(c_userPrefix)) {
            uint userId = string.midRef(c_userPrefix.size()).toUInt(&ok);
            if (ok) {
                return Peer::fromUserId(userId);
            }
        }
        break;
    case 'c': // chat or channel
        if (string.at(3).toLatin1() == 't') {
            if (string.startsWith(c_chatPrefix)) {
                uint chatId = string.midRef(c_chatPrefix.size()).toUInt(&ok);
                if (ok) {
                    return Peer::fromChatId(chatId);
                }
            }
        } else {
            if (string.startsWith(c_channelPrefix)) {
                uint channelId = string.midRef(c_channelPrefix.size()).toUInt(&ok);
                if (ok) {
                    return Peer::fromChannelId(channelId);
                }
            }
        }
        break;
    default:
        break;
    }
    return Peer();
}
コード例 #8
0
ファイル: client.cpp プロジェクト: elipp/wl_gl
void LocalClient::ListenTaskThread::construct_peer_list() {
					
	std::vector<struct peer_info_t> peer_list = process_peer_list_string(buffer + PTCL_HEADER_LENGTH + 1);
		
	for (auto &it : peer_list) {
		//PRINT( "peer data: id = %u, name = %s, ip_string = %s\n", it.id, it.name.c_str(), it.ip_string.c_str());
		auto map_iter = peers.find(it.id);
		if (map_iter == peers.end()) {
			peers.insert(std::make_pair(it.id, Peer(it.id, it.name, it.ip_string, it.color)));
			PRINT("Client \"%s\" (id %u) connected from %s.\n", it.name.c_str(), it.id, it.ip_string.c_str());
		}
		else {
			if (!(map_iter->second.info == it)) {
				PRINT( "warning: peer was found in the peer list, but peer_info_t discrepancies were discovered.\n");
			}
		}
	}


}
コード例 #9
0
ファイル: duktoprotocol.cpp プロジェクト: shuge/dukto
void DuktoProtocol::handleMessage(QByteArray &data, QHostAddress &sender)
{
    char msgtype = data.at(0);

    switch(msgtype)
    {
        case 0x01:  // HELLO (broadcast)
        case 0x02:  // HELLO (unicast)
            data.remove(0, 1);
            if (data != OsLib::retrieveSystemName()) {
                mPeers[sender.toString()] = Peer(sender, data);
                if (msgtype == 0x01) sayHello(sender);
                peerListChanged();
            }
            break;

        case 0x03:  // GOODBYE
            mPeers.remove(sender.toString());
            peerListChanged();
            break;
    }

}
コード例 #10
0
ファイル: MockMessenger.cpp プロジェクト: kevinxw/CIS687-Pr4
//----< test stub >--------------------------------------------
void main() {
	Channel ch("Channel", Peer(8081, "127.0.0.1", 8080));
	MockMessenger mess(ch);
	Message m;
	std::cout<<"\n Reading from run.bat..";
	// test binary message here
	m.fromFile("../run.bat");
	std::cout<<"\n Message length: "<< m.length()
		<<"\n Block size: "<< m.blockSize()
		<<"\n Block number: "<< m.size()
		<<"\n Message name: "<< m.fileName();
	mess(m);	// use messenger to process message

	// test string message here
	Message m2;
	std::cout<<"\n Testing string message..";
	m2.fromString("Test string message");
	std::cout<<"\n Message length: "<< m.length()
		<<"\n Block size: "<< m.blockSize()
		<<"\n Block number: "<< m.size()
		<<"\n Message name: "<< m.fileName();
	mess(m2);
	std::cout<<"\n\n";
}
コード例 #11
0
Discovery::Announce Discovery::Announce::fromBinary(const QByteArray &data) {
	Announce rc;

	if (data.startsWith(QByteArray("BSYNC\0", 6))) {
		libtorrent::entry e = libtorrent::bdecode(data.begin()+6, data.end());
		libtorrent::entry::dictionary_type dict = e.dict();

		MessageType m = (MessageType) dict.at("m").integer();
		std::string peerId = dict.at("peer").string();
		std::string shareHash = dict.at("share").string();
		PeerAddress localAddress, externalAddress;
		if (dict.count("la")) {
			localAddress = PeerAddress::fromBinary(dict.at("la").string());
		}
		if (dict.count("a")) {
			externalAddress = PeerAddress::fromBinary(dict.at("a").string());
		}


		rc = Announce(Secret::fromShareHash(shareHash), Peer(QByteArray(peerId.data(), peerId.length()), localAddress, externalAddress));
	}

	return rc;
}
コード例 #12
0
ファイル: Handshake.cpp プロジェクト: null-null-cn/Cumulus
Handshake::Handshake(Gateway& gateway,Handler& handler,Entity& entity) : ServerSession(0,0,Peer(handler),RTMFP_SYMETRIC_KEY,RTMFP_SYMETRIC_KEY,(Invoker&)handler),
	_gateway(gateway) {
	(bool&)checked=true;

	memcpy(_certificat,"\x01\x0A\x41\x0E",4);
	RandomInputStream().read((char*)&_certificat[4],64);
	memcpy(&_certificat[68],"\x02\x15\x02\x02\x15\x05\x02\x15\x0E",9);

	// Display far id flash side
	EVP_Digest(_certificat,sizeof(_certificat),(unsigned char *)entity.id,NULL,EVP_sha256(),NULL);
}
コード例 #13
0
ServerConnection::ServerConnection(Handler& handler,Session& handshake) : ServerSession(0,0,Peer(handler),NULL,NULL,(Invoker&)handler),_handshake(handshake),_connected(false) {
	RandomInputStream().read((char*)peer.id,ID_SIZE);
}
コード例 #14
0
ファイル: mirac-broker.cpp プロジェクト: 275288698/wds
void MiracBroker::OnTimeout(uint timer_id) {
  Peer()->OnTimerEvent(timer_id);
}
コード例 #15
0
ファイル: Handshake.cpp プロジェクト: agazso/Cumulus
Handshake::Handshake(Gateway& gateway,DatagramSocket& socket,ServerData& data) : Session(0,0,Peer(SocketAddress()),RTMFP_SYMETRIC_KEY,RTMFP_SYMETRIC_KEY,socket,data),
	_gateway(gateway),_signature("\x03\x1a\x00\x00\x02\x1e\x00\x81\x02\x0d\x02",11) {
	
	memcpy(_certificat,"\x01\x0A\x41\x0E",4);
	RandomInputStream().read((char*)&_certificat[4],64);
	memcpy(&_certificat[68],"\x02\x15\x02\x02\x15\x05\x02\x15\x0E",9);

	// Display far id flash side
	UInt8 id[32];
	EVP_Digest(_certificat,sizeof(_certificat),id,NULL,EVP_sha256(),NULL);

	INFO("Id of this cumulus server : %s",Util::FormatHex(id,32).c_str());
}
コード例 #16
0
ファイル: Server.cpp プロジェクト: BackupTheBerlios/pong2-svn
void Server::doNetworking()
{
	grapple_message *message;
	while (grapple_server_messages_waiting(server))
	{
		message = grapple_server_message_pull(server);
		switch (message->type)
		{
		case GRAPPLE_MSG_NEW_USER:
			peer[message->NEW_USER.id] = Peer(grapple_server_client_address_get(server, message->NEW_USER.id));
			std::cerr << "client connected from " << peer[message->NEW_USER.id].name << std::endl;
		break;
		case GRAPPLE_MSG_USER_NAME:
			peer[message->USER_NAME.id].name = message->USER_NAME.name;
		break;
		case GRAPPLE_MSG_USER_MSG:
			{
				grapple_user id = message->USER_MSG.id;
				Buffer buf((char*)message->USER_MSG.data, message->USER_MSG.length);
				switch (buf.getType())
				{
				case READY:
					peer[id].ready = true;

					if (peer.size() > 1) {
						bool ready = true;
						for (std::map<grapple_user, Peer>::iterator i = peer.begin(); i != peer.end(); ++i)
						{
							if (!(*i).second.ready)
							{
								ready = false;
								break;
							}
						}

						if (ready)
							startGame();
					}
				break;
				case PADDLEMOVE:
					{
						unsigned int time = buf.popInt();
						peer[id].player->move(buf.popDouble(), buf.popDouble(), time);
						Vec2f pos = peer[id].player->getPosition();
						Buffer sbuf(PADDLEPOSITION);
						sbuf.pushId(id);
						sbuf.pushDouble(pos.y);
						sbuf.pushDouble(pos.x);
						sendPacket(sbuf, false);
					}
				break;
				case SERVE_BALL:
					peer[id].player->detachBall(ballspeed);
					break;
				case PAUSE_REQUEST:
					togglePause(true, true);
					std::cout << "Player " << peer[id].name << " paused the game." << std::endl;
				break;
				case RESUME_REQUEST:
					togglePause(false, true);
					std::cout << "Player " << peer[id].name << " resumed the game." << std::endl;
				break;
				}
			break;
			}
		case GRAPPLE_MSG_USER_DISCONNECTED:
			std::cout << "Player " << peer[message->USER_DISCONNECTED.id].name << " disconnected!" << std::endl;
			shutdown();
		break;
		}
		grapple_message_dispose(message);
	}
	while (grapple_client_messages_waiting(loopback))
	{
		message=grapple_client_message_pull(loopback);
		switch (message->type)
		{
		case GRAPPLE_MSG_NEW_USER_ME:
			{
				localid = message->NEW_USER.id;
				peer[localid].player = new Player(this, peer[localid].name, FRONT, field.getLength()/2.0f);
				player.push_back(peer[localid].player);
				peer[localid].player->attachBall(&ball[0]);
				output.addMessage(Interface::YOU_SERVE);
				peer[localid].ready = true;
				state = WAITING;
			}
			break;
		}
		grapple_message_dispose(message);
	}
}
コード例 #17
0
ファイル: Network.cpp プロジェクト: tapio/Wendy
bool Host::update(Time timeout)
{
  ENetEvent event;
  bool status = true;
  enet_uint32 ms = (enet_uint32) (timeout * 1000.0);

  while (enet_host_service((ENetHost*) m_object, &event, ms) > 0)
  {
    switch (event.type)
    {
      case ENET_EVENT_TYPE_CONNECT:
      {
        char name[2048];

        enet_address_get_host(&(event.peer->address), name, sizeof(name) - 1);
        name[sizeof(name) - 1] = '\0';

        TargetID peerID;

        if (isClient())
          peerID = SERVER;
        else
          peerID = m_clientIDs.allocateID();

        m_peers.push_back(Peer(event.peer, peerID, name));
        event.peer->data = &(m_peers.back());

        if (m_observer)
          m_observer->onPeerConnected(m_peers.back());

        break;
      }

      case ENET_EVENT_TYPE_DISCONNECT:
      {
        const Peer* peer = static_cast<Peer*>(event.peer->data);

        for (auto p = m_peers.begin();  p != m_peers.end();  p++)
        {
          if (&(*p) == peer)
          {
            uint32 reason;

            if (peer->m_disconnecting)
              reason = peer->m_reason;
            else
              reason = event.data;

            if (m_observer)
              m_observer->onPeerDisconnected(*p, reason);

            m_clientIDs.releaseID(p->targetID());

            m_peers.erase(p);
            break;
          }
        }

        if (isClient())
          status = false;

        event.peer->data = nullptr;
        break;
      }

      case ENET_EVENT_TYPE_RECEIVE:
      {
        if (m_observer)
        {
          if (Peer* peer = static_cast<Peer*>(event.peer->data))
          {
            PacketData data(event.packet->data,
                            event.packet->dataLength,
                            event.packet->dataLength);

            m_observer->onPacketReceived(peer->targetID(), data);
          }
        }

        enet_packet_destroy(event.packet);
        break;
      }

      case ENET_EVENT_TYPE_NONE:
      {
        // This removes a useless warning by Clang
        break;
      }
    }
  }

  enet_host_flush((ENetHost*) m_object);

  m_allocated = 0;

  return status;
}