99 lines
2.4 KiB
C++
99 lines
2.4 KiB
C++
#include <iostream>
|
|
#include <asio.hpp>
|
|
#include <thread>
|
|
#include <mutex>
|
|
#include <queue>
|
|
#include "Tool.hpp"
|
|
#include "nlohmann/json.hpp"
|
|
|
|
using namespace asio::ip;
|
|
using namespace std;
|
|
using namespace asio;
|
|
using json = nlohmann::json;
|
|
|
|
std::mutex mtx;
|
|
|
|
//信息包结构体
|
|
struct MessagePack
|
|
{
|
|
unsigned char* Msg;
|
|
int Length;
|
|
};
|
|
std::queue<std::pair<udp::endpoint, MessagePack*>> messages;
|
|
|
|
//销毁信息包
|
|
void DestoryPck(MessagePack* Pck) {
|
|
delete[] Pck->Msg;
|
|
delete[] Pck;
|
|
}
|
|
|
|
void TotalMessageLogic(udp::endpoint Client, MessagePack* Pck) {
|
|
//得到包长度
|
|
//int Type = ByteLittleToInt((unsigned char*)Pck->Msg);
|
|
|
|
string Scode((char*)Pck->Msg, Pck->Length);
|
|
|
|
char* Code = (char*)Scode.c_str();
|
|
int key[] = skey;
|
|
Cutecode(Code, key);
|
|
|
|
json j = json::parse(Code);
|
|
std::cout << j["op"] << std::endl;
|
|
|
|
DestoryPck(Pck);
|
|
}
|
|
|
|
|
|
//子线程消息处理逻辑
|
|
void handle_messages() {
|
|
while (true) {
|
|
std::pair<udp::endpoint, MessagePack*> message;
|
|
{
|
|
std::lock_guard<std::mutex> lock(mtx);
|
|
if (!messages.empty()) {
|
|
message = messages.front();
|
|
//调用全局处理逻辑
|
|
TotalMessageLogic(message.first, message.second);
|
|
messages.pop();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
io_context ioContext;
|
|
ip::udp::endpoint endpoint(ip::udp::v4(), 12345);
|
|
ip::udp::socket socket(ioContext, endpoint);
|
|
|
|
std::thread message_thread(handle_messages);
|
|
|
|
while (true) {
|
|
char data[1024];
|
|
ip::udp::endpoint senderEndpoint;
|
|
size_t length = socket.receive_from(buffer(data), senderEndpoint);
|
|
|
|
if (length >= 4) {
|
|
uint32_t msgLength = *(reinterpret_cast<uint32_t*>(data));
|
|
|
|
if (length >= msgLength + 4) {
|
|
unsigned char* Str = new unsigned char[msgLength];
|
|
memcpy(Str, data + 4, msgLength);
|
|
MessagePack* Pck = new MessagePack();
|
|
Pck->Msg = Str;
|
|
Pck->Length = msgLength;
|
|
|
|
std::lock_guard<std::mutex> lock(mtx);
|
|
messages.push(std::make_pair(senderEndpoint, Pck));
|
|
}
|
|
else {
|
|
cout << "Incomplete message received, length: " << length << endl;
|
|
}
|
|
}
|
|
else {
|
|
cout << "Invalid message length received" << endl;
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|