Esempio n. 1
0
bool Scene::playerAttach(ServiceID avatarID, SessionID sID)
{

    EntityPtr entity = getEntityByAvatarID(avatarID);
    if (!entity)
    {
        return false;
    }
    entity->_clientSessionID = sID;

    LOGI("Scene::playerAttach avatarName=" << entity->_state.avatarName << " sessionID=" << sID << ", entityID=" << entity->_state.eid);
    SceneSectionNotice section;
    getSceneSection(section.section);
    sendToClient(avatarID, section);

    AddEntityNotice notice;
    for (auto & e : _entitys)
    {
        notice.syncs.push_back(e.second->getClientSyncData());
    }
    if (!notice.syncs.empty())
    {
        sendToClient(avatarID, notice);
    }
    onPlayerAttach(entity);
    return true;
}
Esempio n. 2
0
void Scene::onPlayerInstruction(ServiceID avatarID, ReadStream & rs)
{
    if (avatarID == InvalidAvatarID)
    {
        return;
    }
    if (rs.getProtoID() == MoveReq::getProtoID())
    {
        MoveReq req;
        rs >> req;
        LOGD("MoveReq avatarID[" << avatarID << "] req=" << req);
        auto entity = getEntity(req.eid);
        if (!entity || entity->_state.avatarID != avatarID || entity->_state.etype != ENTITY_PLAYER
            || (req.action != MOVE_ACTION_IDLE && req.action == MOVE_ACTION_FOLLOW && req.action == MOVE_ACTION_PATH)
            || entity->_state.state != ENTITY_STATE_ACTIVE
                    )
        {
            sendToClient(avatarID, MoveResp(EC_ERROR, req.eid, req.action));
            return;
        }
        if (!_move->doMove(req.eid, (MOVE_ACTION)req.action, entity->getSpeed(), req.follow, req.waypoints))
        {
            sendToClient(avatarID, MoveResp(EC_ERROR, req.eid, req.action));
            return;
        }
        if (entity->_skillSys.combating)
        {
            entity->_skillSys.combating = false;
        }

    }
Esempio n. 3
0
void MainWindow::colorChange(QString& newColor)
{
    QTcpSocket *clientTcpSocket = (QTcpSocket*)sender();
    if ((color==newColor) | ((newColor!="green") & (newColor!="blue") & (newColor!="red")) | (state=="off")) {
        messageTo = "FAILED\n";
        sendToClient(clientTcpSocket,messageTo);
        return;
    }
    color=newColor;
    repaint();
    messageTo = "OK\n";
    sendToClient(clientTcpSocket,messageTo);
}
Esempio n. 4
0
void MainWindow::rateChange(QString& newRate)
{
    QTcpSocket *clientTcpSocket = (QTcpSocket*)sender();
    int nRate = newRate.toInt();
    if ((rate==nRate) | ((nRate>5) | (nRate<0)) | (state=="off")) {
        messageTo = "FAILED\n";
        sendToClient(clientTcpSocket,messageTo);
        return;
    }
    rate=nRate;
    killTimer(currentTimerId);
    if (rate!=0) currentTimerId = startTimer(1000/rate);
    messageTo = "OK\n";
    sendToClient(clientTcpSocket,messageTo);
}
Esempio n. 5
0
int main(int argc, char* argv[]) {

	int port;
	int serverSocket, clientSocket;
	struct httpParams httpParam;
	
	system("clear");	

	if (argc != 2) {
		fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]);
		exit(1);
	}

	port = atoi(argv[1]);

	serverSocket = initializeServer(port);	

	while(1) {
	
		clientSocket = getRequest(serverSocket);
		readFromClient(clientSocket);
		httpParam = prepareGetQuery();
		sendToClient(clientSocket, httpParam);
		
		exit(1);

	}
}
Esempio n. 6
0
void Server::slotReadClient()
{
	QTcpSocket* pClientSocket = (QTcpSocket*)sender();
	QDataStream in(pClientSocket);
	//in.setVersion(QDataStream::Qt_4_8);
	for(;;)
	{
		if (!NextBlockSize)
		{
			if (pClientSocket->bytesAvailable() < sizeof(quint16)) break;
			in >> NextBlockSize;
		}
		if (pClientSocket->bytesAvailable() < NextBlockSize) break;
		QTime time;
		QString str;
		in >> time >> str;
		QString strMessage = time.toString() + " " + "Client has sent - " + str;
		//ptxt->append(strMessage);
		emit signal_display(strMessage);
		NextBlockSize = 0;
		str = "Server Response: Recived " + str + "/";
		QString *pstr = &str;
		sendToClient(pClientSocket, *pstr);
	}
}
Esempio n. 7
0
//получаем сообщения от клиента
void InformerTCPServer::slotReadClient()
{
    QTcpSocket *pClientSocket = (QTcpSocket*)sender();
    QDataStream in(pClientSocket);
    in.setVersion(QDataStream::Qt_4_8);
    for(;;){
        if(!m_nNextBlockSize){
            if(pClientSocket->bytesAvailable() < sizeof(quint16))
                break;
        }
        in >> m_nNextBlockSize;

        if (pClientSocket->bytesAvailable() < m_nNextBlockSize) {
            break;
        }
        QTime time;
        QString str;
        in >> time >> str; //записываем сообщения от клиента
        //time записываем себе в лог, например
        //str пишем туда же
        m_nNextBlockSize = 0; //обнуляем счетчик байт

        sendToClient(pClientSocket, trUtf8("Сервак ответил")/*отправить сообщение клиенту "бла-бла-бла"*/);
    }
}
Esempio n. 8
0
void Server::slotReadClient()
{
    QTcpSocket* pClientSocket = (QTcpSocket*)sender();

    QDataStream data(pClientSocket);
    data.setVersion(QDataStream::Qt_5_4);

    QString buf;
    qint16 nextBlockSize = 0;

    for(;;)
    {
        if(!nextBlockSize)
        {
            if(pClientSocket->bytesAvailable() < sizeof(qint16))
                break;

            data >> nextBlockSize;
        }
        if(pClientSocket->bytesAvailable() < nextBlockSize)
            break;

        data >> buf;
        if(!buf.isEmpty())
            sendToClient(pClientSocket, scanner.scanFile(buf));

        nextBlockSize = 0;
    }
}
Esempio n. 9
0
void MainWindow::newConnection()
{
    QTcpSocket* clientTcpSocket = tcpServer->nextPendingConnection();
    connect(clientTcpSocket, SIGNAL(disconnected()), clientTcpSocket, SLOT(deleteLater()));
    connect(clientTcpSocket, SIGNAL(readyRead()), this, SLOT(readClient()));
    sendToClient(clientTcpSocket, "Server Response: Connected!");
}
Esempio n. 10
0
void onQuit() {
    if (childPID != 0) {
        msgctl(clientQueueID, IPC_RMID, NULL);
        sendToClient(serverQueueID, STOP, clientID, 0);
        exit(1);
    }
}
Esempio n. 11
0
void CGalconServer::sendToConnectedClients( const QString& str )
{
   for (SocketsMap::iterator it = m_connectedSockets.begin(); it != m_connectedSockets.end(); ++it)
   {
      sendToClient(it->second, str);
   }
}
Esempio n. 12
0
//-------------------------------------------------------------------------------------
void Proxy::onDefDataChanged(const PropertyDescription* propertyDescription, 
		PyObject* pyData)
{
	uint32 flags = propertyDescription->getFlags();

	if((flags & ED_FLAG_BASE_AND_CLIENT) <= 0 || clientMailbox_ == NULL)
		return;

	// 创建一个需要广播的模板流
	MemoryStream* mstream = MemoryStream::ObjPool().createObject();

	propertyDescription->getDataType()->addToStream(mstream, pyData);

	Mercury::Bundle* pBundle = Mercury::Bundle::ObjPool().createObject();
	(*pBundle).newMessage(ClientInterface::onUpdatePropertys);
	(*pBundle) << id();

	if(scriptModule_->usePropertyDescrAlias())
		(*pBundle) << propertyDescription->aliasIDAsUint8();
	else
		(*pBundle) << propertyDescription->getUType();

	pBundle->append(*mstream);
	
	g_privateClientEventHistoryStats.trackEvent(scriptName(), 
		propertyDescription->getName(), 
		pBundle->currMsgLength());

	sendToClient(ClientInterface::onUpdatePropertys, pBundle);
	MemoryStream::ObjPool().reclaimObject(mstream);
}
Esempio n. 13
0
bool Scene::enterScene(ServiceID avatarID, const std::string & token, SessionID sID)
{
    EntityPtr entity = getUserEntity(avatarID);
    if (!entity)
    {
        return false;
    }
    if (entity->_token != token)
    {
        return false;
    }
    entity->_clientSessionID = sID;
    if (!getEntity(entity->_info.eid))
    {
        addEntity(entity);
    }
    FillSceneNotice notice;
    EntityFullInfo info;
    for (auto kv : _entitys)
    {
        kv.second->pickProto(info);
        notice.entitys.push_back(info);
    }
    notice.serverTime = getFloatNowTime();
    notice.sceneStartTime = _startTime;
    notice.sceneEndTime = _endTime;
    sendToClient(avatarID, notice);
    return true;
}
void SrvSocket::sendToAll(std::string message, bool acknowledgeRequired)
{
	for(unsigned int i=0; i < _csock.size(); i++)
	{
		sendToClient(i, message, acknowledgeRequired);
	}
}
Esempio n. 15
0
//создаем сокет для соединения клиентов
void InformerTCPServer::slotNewConnection()
{
    QTcpSocket *pClientSocket = m_ptcpServer->nextPendingConnection();
    connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater()));
    connect(pClientSocket, SIGNAL(readyRead()),this, SLOT(slotReadClient()));
    sendToClient(pClientSocket, trUtf8("Сервак ответил")/*отправить сообщение клиенту "бла-бла-бла"*/);
}
Esempio n. 16
0
//-------------------------------------------------------------------------------------
void Proxy::initClientCellPropertys()
{
	if(getClientMailbox() == NULL)
		return;

	Mercury::Bundle* pBundle = Mercury::Bundle::ObjPool().createObject();
	(*pBundle).newMessage(ClientInterface::onUpdatePropertys);
	(*pBundle) << this->getID();

	ENTITY_PROPERTY_UID spaceuid = ENTITY_BASE_PROPERTY_UTYPE_SPACEID;

	Mercury::FixedMessages::MSGInfo* msgInfo = 
		Mercury::FixedMessages::getSingleton().isFixed("Property::spaceID");

	if(msgInfo != NULL)
	{
		spaceuid = msgInfo->msgid;
	}
	
	(*pBundle) << spaceuid << this->getSpaceID();

	MemoryStream* s = MemoryStream::ObjPool().createObject();
	addPositionAndDirectionToStream(*s);
	(*pBundle).append(s);
	MemoryStream::ObjPool().reclaimObject(s);

	// celldata获取客户端感兴趣的数据初始化客户端 如:ALL_CLIENTS
	s = MemoryStream::ObjPool().createObject();
	addCellDataToStream(ED_FLAG_ALL_CLIENTS|ED_FLAG_CELL_PUBLIC_AND_OWN|ED_FLAG_OWN_CLIENT, s);
	(*pBundle).append(*s);
	MemoryStream::ObjPool().reclaimObject(s);
	//getClientMailbox()->postMail((*pBundle));
	//Mercury::Bundle::ObjPool().reclaimObject(pBundle);
	sendToClient(ClientInterface::onUpdatePropertys, pBundle);
}
Esempio n. 17
0
void MainWindow::stateChange(QString& newState)
{
    QTcpSocket *clientTcpSocket = (QTcpSocket*)sender();
    if ((state==newState) | ((state!="on") & (state!="off"))) {
        messageTo = "FAILED\n";
        sendToClient(clientTcpSocket,messageTo);
        return;
    }
    state=newState;
    if (state=="on") {
        if (rate!=0)    currentTimerId = startTimer(1000/rate);
    } else if (state=="off") {
        if (rate!=0)    killTimer(currentTimerId);
    }
    messageTo = "OK\n";
    sendToClient(clientTcpSocket,messageTo);
}
Esempio n. 18
0
void Worker::onBackendResponse(Backend *backend)
{
	LOG("backend response");
	Buffer &resp = backend->getResponse();
	Connection *client = backend->getClient();
	if(client && resp.size()){
		sendToClient(client, &resp);
	}
}
Esempio n. 19
0
void SessionOp::sendDisconnectToClient()
{
    DisconnectMsg_SN msg;
    auto& fields = msg.fields();
    auto& durationField = std::get<decltype(msg)::FieldIdx_duration>(fields);
    durationField.setMode(comms::field::OptionalMode::Missing);
    sendToClient(msg);

}
Esempio n. 20
0
void Server::sendLongArray(std::vector<int> arr)
{
    uint32_t *arr_raw = new uint32_t[(size_t)arr.size()];
    for (size_t i = 0; i < arr.size(); ++i) {
        arr_raw[i] = htonl((uint32_t)arr[i]);
    }

    sendToClient(arr_raw, sizeof(uint32_t) * arr.size());
    delete [] arr_raw;
}
// send data to all clients
void ServerNetworkManager::sendToAll(unsigned int iteration, unsigned int packet_type, unsigned int object_id, CommandTypes command_type, unsigned int data_size) {
    SOCKET currentSocket;
    std::map<unsigned int, SOCKET>::iterator iter;
	int iSendResult;

    for (iter = sessions.begin(); iter != sessions.end(); iter++) {
        currentSocket = iter->second;
		iSendResult = sendToClient(currentSocket, iteration, packet_type, object_id, command_type, data_size);
    }
}
Esempio n. 22
0
void MessageWidget::sendSms(QString number,QString message)
{
    if (number.contains('('))
    {
        number.chop(1);
        number = number.mid(number.indexOf("(")+1,number.length());
    }
    sendToClient("SEND_SMS:"+number.toLatin1()+":"+message.toLatin1());

    //addSMS(, "1",QString::number(QDateTime::currentMSecsSinceEpoch()),number,"1","outbox",message);
}
Esempio n. 23
0
int main(int argc, char **argv) {
    text = malloc(MAX_MESSAGE_LEN);
    if ((serverQueueID = msgget(ftok(getenv("HOME"), 0), 0)) == -1)
        printError("Coudlnt get server queue");

    if ((clientQueueID = msgget(ftok(getenv("HOME"), getpid()), IPC_CREAT | 0666)) == -1)
        printError("Coudlnt get client queue");

    atexit(onQuit);

    sendToClient(serverQueueID, INIT, ftok(getenv("HOME"), getpid()), 0);
    Message message = receiveData(clientQueueID);
    clientID = message.value;

    printf("ID: %d\n", clientID);
    if ((childPID = fork()) == 0) {
        while (1) {
            Message received = receiveData(clientQueueID);
            if (received.type == ECHO){
                printf("GOT MESSAGE ECHO: %s\n", received.text);
                printf("-------------\n");
            }
            if (received.type == STOP) {
                printf("GOT MESSAGE STOP");
                kill(getppid(), SIGUSR1);
                exit(0);
            }
        }
    } else {
        signal(SIGINT, handleCtrlC);
        signal(SIGUSR1, handleSIGUSR);
        char *comm = malloc(MAX_MESSAGE_LEN);
        if (argc > 2) {
            FILE *fd;
            if(strcmp(argv[1], "READ") != 0)
                printError("NOT READ?");

            if ((fd = fopen(argv[2], "r")) != NULL) {
                char *input = malloc(MAX_FILE_SIZE);
                fread(input, sizeof(char), MAX_FILE_SIZE, fd);
                comm = strtok(input, "\n");
                while (comm != NULL) {
                    handleInput(comm, strlen(comm));
                    comm = strtok(NULL, "\n");
                }
            }
        }
        size_t MAX_MESSAGE_LEN_SIZE_T = MAX_MESSAGE_LEN + 6;
        while (1) {
            size_t size = getline(&comm, &MAX_MESSAGE_LEN_SIZE_T, stdin);
            handleInput(comm, size);
        }
    }
}
Esempio n. 24
0
void Worker::doSendAllMsg(RouterMsg *pMsg)
{
	ClientList::const_iterator it;
	int n = 0;
	for(it = arrClients.begin(); it != arrClients.end(); ++it){
		Connection *pClient = it->second;
		sendToClient(pClient, pMsg->data, pMsg->len);
		n++;
	}
	
	LOG("sendall msg n=%d", n);
}
Esempio n. 25
0
void Server::slotNewConnection()
{
	QTcpSocket* pClientSocket = ptcpServer->nextPendingConnection();
	connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater()));
	connect(pClientSocket, SIGNAL(readyRead()), this, SLOT(slotReadClient()));
	QString str = "Server Response: Connected!!";
	QString* pstr = &str;
	sendToClient(pClientSocket, *pstr);
	QString buf = "New client connected: Новий клієнт" + pClientSocket->peerAddress().toString();
	emit signal_display(buf);
	clients.insert(pClientSocket->peerAddress().toString(), pClientSocket);
}
Esempio n. 26
0
void MessageWidget::sendSmsThread(QString message)
{

    MessageThread thread = this->messageThreadModel.getThread(this->sortModel.filterRegExp().pattern());
    QString number = thread.getNumber();

    if (number == "")
        return;
    sendToClient("SEND_SMS:"+number.toLatin1()+":"+message.toLatin1());

    addSMS(thread.getId(), "1",QString::number(QDateTime::currentMSecsSinceEpoch()),number,"1","outbox",message);
}
Esempio n. 27
0
//FONCTION : réagit selon le message passé en paramètre
void Server::processRequest(const QString &message,QTcpSocket*socket)
{
    QStringList req = message.split(QRegExp("@"));
    int idClient = getIndexFromSocket(socket);

    if(req[0].compare("isSending")==0)
    {
        bool statePlaying=req[1].toInt();
        qDebug() << "SERVER pipeline will change because user streaming stopped";

        clients[idClient].isSending=statePlaying;
        setPipeline();
    }
    else if (req[0].compare("name")==0)
    {
        int databaseResult = verifyDataBase(req[1],req[2]);
        if(databaseResult==-1 || alreadyConnected(req[1]))
        {
            //si le client n'est pas dans la base, on le kick
            qDebug() << "SERVER kicked " + req[1];
            clients[idClient].sock->abort();
        }
        else
        {
            clients[idClient].name=req[1];
            sendToClient("port@"+QString::number(allocatedPort),clients[idClient].sock);
            clients[idClient].port=allocatedPort;
            clients[idClient].isTeacher=databaseResult;
            clients[idClient].isSending=true;
            allocatedPort++;
            sendToClient("isTeacher@"+QString::number(databaseResult),clients[idClient].sock);
            setPipeline();
        }
    }
    else if (req[0].compare("chat")==0)
    {
        sendToAll(message);
    }
}
Esempio n. 28
0
void MainWindow::ServerOperations(QByteArray data)
{
    QString Line(data);
    QStringList dataList = Line.split(" ");
    bool tf=false;
    QTcpSocket* clientTcpSocket = (QTcpSocket*)sender();
    for (int i=0;i<Commands.size();i++)
        if (dataList[0] == Commands[i]) tf=true;
    if (!tf) {
        messageTo = "FAILED\n";
        sendToClient(clientTcpSocket,messageTo);
        return;
    }
    QStringList typeCommand = dataList[0].split("-");
    if (typeCommand[0]=="set") {
        dataList[1].chop(1);
        if (typeCommand[2]=="state")        stateChange(dataList[1]);
        else if (typeCommand[2]=="color")   colorChange(dataList[1]);
        else if (typeCommand[2]=="rate")    rateChange(dataList[1]);
    } else  if (typeCommand[0]=="get") {
        typeCommand[2].chop(1);
        if (typeCommand[2]=="state") {
            messageTo = "OK " + state + "\n";
            sendToClient(clientTcpSocket,messageTo);
        } else if (typeCommand[2]=="color") {
            messageTo = "OK " + color.name() + "\n";
            sendToClient(clientTcpSocket,messageTo);
        } else if (typeCommand[2]=="rate") {
            messageTo = "OK " + QString::number(rate) + "\n";
            sendToClient(clientTcpSocket,messageTo);
        } else {
            messageTo = "FAILED\n";
            sendToClient(clientTcpSocket,messageTo);
        }
    }
}
Esempio n. 29
0
void Worker::doSendMsg(RouterMsg *pMsg)
{
	int pos = 0;
	while(pos + SID_LENGTH <= pMsg->slen)
	{
		std::string sid(pMsg->data + pos, SID_LENGTH);
		ClientList::const_iterator it = arrClients.find(sid);
		if(it != arrClients.end()){
			Connection *pClient = it->second;
			LOG("send msg, sid=%s", sid.c_str());
			sendToClient(pClient, pMsg->data + pMsg->slen, pMsg->len);
		}else{
			LOG("not found client, sid=%s", sid.c_str());
		}
		
		pos+= SID_LENGTH;
	}
}
Esempio n. 30
0
void Worker::doChannelPub(RouterMsg *pMsg)
{
	//频道名称在session域
	std::string chname(pMsg->data, pMsg->slen);
	ChannelList::const_iterator it = arrChannels.find(chname);
	if(it == arrChannels.end()){
		return ;
	}
	
	const ConnectionSet &clients = it->second;
	ConnectionSet::const_iterator it2;
	for(it2 = clients.begin(); it2 != clients.end(); ++it2){
		Connection *pClient = it2->first;
		ClientData *pClientData = (ClientData*)pClient->getData();
		sendToClient(pClient, pMsg->data + pMsg->slen, pMsg->len);
		
		LOG("send channel msg to: %s", pClientData->session.getId());
	}
}