inline void UDTProtocol::convertDataToPacket(UDTSOCKET socket, QByteArray *data){ QString ip = ""; quint16 port = 0; getAddressInfoFromSocket(socket, &ip, &port); QDataStream in(data, QIODevice::ReadOnly); in.setVersion(QDataStream::Qt_4_7); QVariant v; in >> v; if (v.canConvert<Packet>()){ Packet *packet = PacketHandlerBase::getPacket(); *packet = v.value<Packet>(); packet->setTransmissionProtocol(TP_UDT); packet->setSocketID(socket); packet->setPeerHostAddress(QHostAddress(ip)); packet->setPeerHostPort(port); // packet->setLocalHostAddress(m_udpSocket->localAddress()); // packet->setLocalHostPort(m_udpSocket->localPort()); // m_packetHandlerBase->appendIncomingPacket(packet); emit packetReceived(packet); }else{ qWarning()<<"ERROR! Can not convert UDT data to Packet!"; } }
void TCPServer::processData(int socketID, QByteArray *data){ QString address; quint16 port; getAddressInfoFromSocket(socketID, &address, &port, true); QDataStream in(data, QIODevice::ReadOnly); in.setVersion(QDataStream::Qt_4_7); QVariant v; in >> v; if (v.canConvert<Packet>()){ Packet *packet = PacketHandlerBase::getPacket(); *packet = v.value<Packet>(); packet->setTransmissionProtocol(TP_UDT); packet->setSocketID(socketID); packet->setPeerHostAddress(QHostAddress(address)); packet->setPeerHostPort(port); // packet->setLocalHostAddress(m_udpSocket->localAddress()); // packet->setLocalHostPort(m_udpSocket->localPort()); // m_packetHandlerBase->appendIncomingPacket(packet); emit packetReceived(packet); }else{ qWarning()<<"ERROR! Can not convert TCP data to Packet!"; } }
void Connection::onDataReady() { buffer = readAll(); // The TCP protocol might stack multiple packets into a bigger one // if the packets are sufficiently small. Therefore, we have to keep // reading until we are sure we have received it all. start: if (readSize == 0) { // Wait until we have enough data to read the 32-bit int. if (buffer.size() < sizeof(readSize)) { return; } QDataStream stream(&buffer, QIODevice::ReadOnly); stream >> readSize; // Remove the data of the size just read from the buffer. buffer = buffer.mid(sizeof(readSize)); } if (buffer.size() == readSize) { emit packetReceived(StatePacket::fromData(buffer.left(readSize))); buffer = buffer.mid(readSize); readSize = 0; // See if there's more. goto start; } }
bool UdpServerListener::startListening() { connectionsTimer.start(); qWarning() << this->metaObject()->className() << "startListening"; if (udpSocket != nullptr) { // already listening return true; } udpSocket = new(std::nothrow) QUdpSocket(this); if (udpSocket == nullptr) { qFatal("Cannot allocate memory for udpSocket X{"); } udpSocket->moveToThread(&serverThread); connect(udpSocket, SIGNAL(readyRead()), this, SLOT(packetReceived())); if (!udpSocket->bind(hostAddress, hostPort)) { emit log(tr("UDP server error: %1").arg(udpSocket->errorString()),ID,Pip3lineConst::LERROR); delete udpSocket; udpSocket = nullptr; return false; } emit log(tr("UDP server started %1:%2").arg(hostAddress.toString()).arg(hostPort), ID, Pip3lineConst::LSTATUS); emit started(); return true; }
void SerialPortManager::handleReadyRead() { // readReady() has been emitted, so now we clear the m_serialPort buffer // QByteArray data = m_serialPort->readAll(); QByteArray data; while(!m_serialPort->atEnd()){ data+=m_serialPort->readAll(); } emit packetReceived(data); }
looptest::looptest() { qDebug() << "[LoopTest][INFO]: Program started" << endl; Wakeproto sx; connect(&sx,SIGNAL(packetReceived(QByteArray)),this,SLOT(packet_rcvd(QByteArray))); QByteArray data; data = sx.createpacket(219,220,"senddata"); sx.getpacket(data); // data = sx.createpacket(220,220,"senddata"); sx.getpacket(data); }
bool ZeroMqConnection::dealerReceive() { zmq::message_t message; if(m_socket->recv(&message, ZMQ_NOBLOCK)) { int size = message.size(); PacketType packet(static_cast<char*>(message.data()), size); emit packetReceived(packet, EndpointIdType()); return true; } return false; }
WakeServer::WakeServer(QObject *parent) : QObject(parent) { wproto = new Wakeproto(); connect(wproto,SIGNAL(packetReceived(QByteArray)),this,SLOT(packet_rcvd(QByteArray))); QTextCodec* codec = QTextCodec::codecForName("UTF8"); QTextCodec::setCodecForLocale(codec); tcpServer = new QTcpServer(this); connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newuser())); if (!tcpServer->listen(QHostAddress::Any, 8888)) { qDebug() << QObject::tr("Unable to start the server: %1.").arg(tcpServer->errorString()); } else { qDebug() << tcpServer->isListening() << "TCPSocket listen on port"; qDebug() << QString::fromUtf8("Server running!"); } }
void byteReceived(unsigned char c) { switch (rx.state) { case WAIT: if (c == START_BYTE) rx.state = START; break; case START: if (isValidCommand(c)) { rx.cmd = c; rx.state = LENGTH; } else { rx.state = WAIT; } break; case LENGTH: rx.length = c; rx.i = 0; rx.checksum = 0; rx.state = DATA; break; case DATA: rx.data[rx.i++] = c; rx.checksum ^= c; if (rx.i == rx.length) rx.state = CHECKSUM; break; case CHECKSUM: if (c == rx.checksum) packetReceived(); rx.state = WAIT; break; default: rx.state = WAIT; break; } // end switch }
void LocalSocketConnection::readSocket() { if(!m_socket->isValid()) return; if (m_holdRequests) return; if (m_socket->bytesAvailable() == 0) return; PacketType packet; (*m_dataStream) >> packet; emit packetReceived(packet, EndpointIdType()); // Check again in 50 ms if no more data is available, or immediately if there // is. This helps ensure that burst traffic is handled robustly. QTimer::singleShot(m_socket->bytesAvailable() > 0 ? 0 : 50, this, SLOT(readSocket())); }
NRF::SPI::Status NRF::SE8R01::handleIRQ() { Status status = getStatus(); uint8_t length = 0; uint8_t data[32]; TxObserve txObserve; if (status.b.dataReceived) { getRxPacketSize(&length); readPacket(data, length); } if (packetTransmitted && (status.b.maxRetrans || status.b.dataSent)) readReg(Reg_TxObserve, &txObserve, sizeof(txObserve)); if (status.b.maxRetrans || status.b.dataSent || status.b.dataReceived) status = writeReg(Reg_Status, &status, sizeof(status)); if (packetReceived && status.b.dataReceived) packetReceived(status.b.rxPipe, data, length); if (packetTransmitted && (status.b.maxRetrans || status.b.dataSent)) packetTransmitted(!status.b.maxRetrans, txObserve.b.retransCount); return status; }
void XBeeNodeImpl::handlePacketReceived(const XBeeFrame& frame) { ReceivePacket receivePacket; Poco::MemoryInputStream mistr(frame.data(), frame.dataSize()); Poco::BinaryReader reader(mistr, Poco::BinaryReader::NETWORK_BYTE_ORDER); if (frame.type() == XBeeFrame::XBEE_FRAME_RECEIVE_PACKET_64BIT_ADDRESS) { deserializeDeviceAddress(reader, receivePacket.deviceOrNetworkAddress); } else { deserializeNetworkAddress(reader, receivePacket.deviceOrNetworkAddress); } reader >> receivePacket.rssi >> receivePacket.options; deserializeData(reader, reader.available(), receivePacket.payload); packetReceived(receivePacket); }
bool ZeroMqConnection::routerReceive() { zmq::message_t address; if (m_socket->recv(&address, ZMQ_NOBLOCK)) { int size = address.size(); EndpointIdType replyTo(static_cast<char*>(address.data()), size); // Now receive the message zmq::message_t message; if(!m_socket->recv(&message, ZMQ_NOBLOCK)) { qWarning() << "Error no message body received"; return true; } PacketType packet(static_cast<char*>(message.data()), message.size()); emit packetReceived(packet, replyTo); return true; } return false; }
void StunClient::processResponse(QByteArray resp, QString peer_addr) { u08bits rbuf[STUN_BUFFER_SIZE]; size_t rlen = 0; stun_buffer buf; QString mapped_addr; u08bits addr_buff[STUN_BUFFER_SIZE] = {0}; rlen = resp.length(); memcpy(rbuf, resp.data(), resp.length()); buf.len = resp.length(); memcpy(buf.buf, resp.data(), resp.length()); if (!stun_is_command_message(&buf)) { qDebug()<<resp.length()<<("The response is not a STUN message")<<peer_addr; // should be a relayed raw UDP packet to peerA emit packetReceived(resp, peer_addr); return; } u16bits stun_method; u16bits stun_msg_type; stun_method = stun_get_method_str(buf.buf, buf.len); stun_msg_type = stun_get_msg_type_str(buf.buf, buf.len); qDebug()<<"method:"<<stun_method<<getMethodName(stun_method)<<",msg type:"<<stun_msg_type; if (stun_method == STUN_METHOD_BINDING) { } else { this->debugStunResponse(resp); } // channel data if (stun_is_indication(&buf)) { u16bits chan_no; size_t blen = 0; qDebug()<<"indication data:"<<buf.len; stun_attr_ref t_attr = stun_attr_get_first_by_type(&buf, STUN_ATTRIBUTE_DATA); const u08bits *t_value = stun_attr_get_value(t_attr); blen = stun_attr_get_len(t_attr); QString xor_peer_addr = getStunAddress(resp, STUN_ATTRIBUTE_XOR_PEER_ADDRESS); qDebug()<<"is chan msg:"<<stun_is_channel_message_str(t_value, &blen, &chan_no, 0); qDebug()<<"chan no:"<<chan_no<<blen<<xor_peer_addr; emit this->packetReceived(QByteArray((char*)t_value + 4, blen - 4), xor_peer_addr); return; } if (!stun_is_response(&buf)) { qDebug()<<resp.length()<<("The response is not a reponse message\n"); return; } if (!stun_is_success_response(&buf)) { int err_code = 0; u08bits err_msg[1025] = "\0"; size_t err_msg_size = sizeof(err_msg); if (stun_is_error_response(&buf, &err_code, err_msg, err_msg_size)) { printf("The response is an error %d (%s)\n", err_code, (char*) err_msg); } else { printf("The response is an unrecognized error\n"); } // test unauth u08bits realm[128] = {0}; u08bits nonce[256] = {0}; if (stun_is_challenge_response_str(buf.buf, buf.len, &err_code, err_msg, err_msg_size, realm, nonce)) { qDebug()<<err_code; qDebug()<<err_code<<(char*)err_msg<<(char*)realm<<(char*)nonce; m_realm = QByteArray((char*)realm); m_nonce = QByteArray((char*)nonce); if (stun_method == STUN_METHOD_ALLOCATE) { this->allocate((char*)realm, (char*)nonce); } if (stun_method == STUN_METHOD_CHANNEL_BIND) { QThread::msleep(100); this->channelBind(m_peer_addr); } } if (err_code == 437) { assert(err_code != 437); // allocate mismatch } if (err_code == 438) { assert(err_code != 438); // stale nonce } if (err_code == 486) { assert(err_code != 486); // allocate quota reached } return; } if (stun_is_binding_response(&buf)) { ioa_addr reflexive_addr; addr_set_any(&reflexive_addr); if (stun_attr_get_first_addr(&buf, STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, &reflexive_addr, NULL) >= 0) { stun_attr_ref sar = stun_attr_get_first_by_type_str(buf.buf, buf.len, STUN_ATTRIBUTE_OTHER_ADDRESS); if (sar) { // *rfc5780 = 1; printf("\n========================================\n"); // printf("RFC 5780 response %d\n",++counter); ioa_addr other_addr; stun_attr_get_addr_str((u08bits *) buf.buf, (size_t) buf.len, sar, &other_addr, NULL); sar = stun_attr_get_first_by_type_str(buf.buf, buf.len, STUN_ATTRIBUTE_RESPONSE_ORIGIN); if (sar) { ioa_addr response_origin; stun_attr_get_addr_str((u08bits *) buf.buf, (size_t) buf.len, sar, &response_origin, NULL); addr_debug_print(1, &response_origin, "Response origin: "); } addr_debug_print(1, &other_addr, "Other addr: "); } addr_debug_print(1, &reflexive_addr, "UDP reflexive addr"); addr_to_string(&reflexive_addr, addr_buff); } else { printf("Cannot read the response\n"); } // emit got addr if (strlen((char*)addr_buff) > 0) { mapped_addr = QString((char*)addr_buff); emit this->mappedAddressRecieved(mapped_addr); } return; } // end bind resp if (stun_method == STUN_METHOD_ALLOCATE) { m_relayed_addr = this->getStunAddress(resp, STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS); this->saveAllocatePuples(m_realm, m_nonce); emit this->allocateDone(m_relayed_addr); if (!m_channel_refresh_timer) { m_channel_refresh_timer = new QTimer(); QObject::connect(m_channel_refresh_timer, &QTimer::timeout, this, &StunClient::onRefreshTimeout); } if (!m_channel_refresh_timer->isActive()) { m_channel_refresh_timer->start(m_channel_refresh_timeout); } } if (stun_method == STUN_METHOD_CREATE_PERMISSION) { if (!m_permission_keepalive_timer) { emit this->createPermissionDone(); } if (!m_permission_keepalive_timer) { m_permission_keepalive_timer = new QTimer(); QObject::connect(m_permission_keepalive_timer, &QTimer::timeout, this, &StunClient::onPermKATimeout); } if (!m_permission_keepalive_timer->isActive()) { m_permission_keepalive_timer->start(m_permission_keepalive_timeout); } } if (stun_method == STUN_METHOD_CHANNEL_BIND) { emit this->channelBindDone(m_relayed_addr); } if (stun_method == STUN_METHOD_REFRESH) { qDebug()<<"refresh responsed."; } }
void SerialManager::handlePacketReceived(int id) { emit packetReceived(id); }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); app.setOrganizationName("arksaw"); app.setApplicationName("tisserver"); // Initialize settings stuff QSettings::setDefaultFormat(QSettings::IniFormat); QSettings settings; settings.setValue("port", 50000); settings.sync(); Console console; Database database; SessionManager sessionManager(0, &database); GameThread game(0, &database, &sessionManager); UdpServer udpServer; qRegisterMetaType<Packet>("Packet"); qRegisterMetaType<QHostAddress>("QHostAddress"); // Console signals/slots QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)), &sessionManager, SLOT(runCommand(CommandType,QStringList))); QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)), &game, SLOT(runCommand(CommandType,QStringList)), Qt::DirectConnection); // Need direct connection from cross-thread signals to blocked thread QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)), &udpServer, SLOT(runCommand(CommandType,QStringList))); // Database signals/slots QObject::connect(&database, SIGNAL(writeToConsole(QString)), &console, SLOT(writeLine(QString)), Qt::QueuedConnection); // SessionManager signals/slots QObject::connect(&sessionManager, SIGNAL(writeToConsole(QString)), &console, SLOT(writeLine(QString))); QObject::connect(&sessionManager, SIGNAL(responseReady(Packet,QHostAddress,quint16)), &udpServer, SLOT(sendResponse(Packet,QHostAddress,quint16)), Qt::QueuedConnection); // GameThread signals/slots QObject::connect(&game, SIGNAL(writeToConsole(QString)), &console, SLOT(writeLine(QString))); QObject::connect(&game, SIGNAL(updatePacketReady(Packet)), &sessionManager, SLOT(sendUpdatePacket(Packet)), Qt::QueuedConnection); // UdpServer signals/slots QObject::connect(&udpServer, SIGNAL(writeToConsole(QString)), &console, SLOT(writeLine(QString))); QObject::connect(&udpServer, SIGNAL(packetReceived(Packet,QHostAddress,quint16)), &sessionManager, SLOT(processPacket(Packet,QHostAddress,quint16)), Qt::DirectConnection); // Set up threading. QThread thread; game.moveToThread(&thread); thread.start(); thread.connect(&thread, SIGNAL(finished()), &app, SLOT(quit())); // Invoke with Qt::QueuedConnection since the Qt event loop isn't up yet QMetaObject::invokeMethod(&database, "init", Qt::QueuedConnection); QMetaObject::invokeMethod(&sessionManager, "start", Qt::QueuedConnection); QMetaObject::invokeMethod(&game, "start", Qt::QueuedConnection); QMetaObject::invokeMethod(&udpServer, "start", Qt::QueuedConnection); // Run the primary thread's main event loop. // exec() will return when we stop the main event loop via a signal return app.exec(); }
int ClientNetwork::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: packetReceived(); break; case 1: packetCorrupted(); break; case 2: pingUpdated((*reinterpret_cast< quint32(*)>(_a[1]))); break; case 3: chatReceived((*reinterpret_cast< CLID(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3])),(*reinterpret_cast< ENUM_TYPE(*)>(_a[4]))); break; case 4: serverInformationsChanged((*reinterpret_cast< ServerInformations(*)>(_a[1]))); break; case 5: clientIDChanged((*reinterpret_cast< CLID(*)>(_a[1]))); break; case 6: nicknameChanged((*reinterpret_cast< CLID(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 7: error((*reinterpret_cast< ENUM_TYPE(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 8: clientVoted((*reinterpret_cast< CLID(*)>(_a[1])),(*reinterpret_cast< CLID(*)>(_a[2]))); break; case 9: newGameMaster((*reinterpret_cast< CLID(*)>(_a[1]))); break; case 10: serverName((*reinterpret_cast< QString(*)>(_a[1]))); break; case 11: motdChanged((*reinterpret_cast< QString(*)>(_a[1]))); break; case 12: gameLaunched(); break; case 13: narrationChanged((*reinterpret_cast< QString(*)>(_a[1]))); break; case 14: mapChanged((*reinterpret_cast< MapPtr(*)>(_a[1]))); break; case 15: mapFlare((*reinterpret_cast< QPoint(*)>(_a[1])),(*reinterpret_cast< CLID(*)>(_a[2]))); break; case 16: scriptToGMMsg((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 17: scriptToOwnerMsg((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 18: scriptActionMsg((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 19: scriptToPlayerMsg((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 20: scriptMsg((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 21: scriptError((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 22: updateEntities((*reinterpret_cast< const QList<EntityInformations>(*)>(_a[1]))); break; case 23: updateEntity((*reinterpret_cast< const EntityInformations(*)>(_a[1]))); break; case 24: entityDeleted((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 25: scriptReceived((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 26: ressourcesUpdated((*reinterpret_cast< const QMap<QString,RSID>(*)>(_a[1]))); break; case 27: connectionEtablished(); break; case 28: connectionLost(); break; case 29: diceRolled((*reinterpret_cast< CLID(*)>(_a[1])),(*reinterpret_cast< quint16(*)>(_a[2])),(*reinterpret_cast< quint16(*)>(_a[3]))); break; case 30: sanctionned((*reinterpret_cast< CLID(*)>(_a[1])),(*reinterpret_cast< ENUM_TYPE(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3]))); break; case 31: clientJoined((*reinterpret_cast< CLID(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 32: clientLeft((*reinterpret_cast< CLID(*)>(_a[1]))); break; case 33: playSound((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 34: syncLibs((*reinterpret_cast< QList<SoundLibInformations>(*)>(_a[1]))); break; case 35: syncLanguagesList((*reinterpret_cast< QList<QPair<QString,QString> >(*)>(_a[1]))); break; case 36: syncDictionariesList((*reinterpret_cast< QStringList(*)>(_a[1]))); break; case 37: syncScriptList((*reinterpret_cast< QStringList(*)>(_a[1]))); break; case 38: updateCharacterList((*reinterpret_cast< const QStringList(*)>(_a[1]))); break; case 39: send((*reinterpret_cast< Packet*(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; case 40: send((*reinterpret_cast< Packet*(*)>(_a[1]))); break; case 41: send((*reinterpret_cast< Packet(*)>(_a[1]))); break; case 42: send((*reinterpret_cast< qint32(*)>(_a[1])),(*reinterpret_cast< const QByteArray(*)>(_a[2]))); break; case 43: ping(); break; case 44: { qint32 _r = getPing(); if (_a[0]) *reinterpret_cast< qint32*>(_a[0]) = _r; } break; case 45: { QString _r = serverIP(); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 46: { quint16 _r = serverPort(); if (_a[0]) *reinterpret_cast< quint16*>(_a[0]) = _r; } break; case 47: flush(); break; case 48: connection(); break; case 49: disconnection(); break; case 50: { bool _r = setServer((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< quint16(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 51: connected(); break; case 52: disconnected(); break; case 53: dataReceived(); break; case 54: socketError((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break; case 55: operatePacket((*reinterpret_cast< Packet*(*)>(_a[1]))); break; default: ; } _id -= 56; } return _id; }