Я получаю следующую ошибку в своем инструменте разработки для порта 8080, который определенно работает:
Попытка получить данные из http://localhost:8080/simdata
GET http://localhost:8080/simdata net::ERR_CONNECTION_RESET
Для неиспользуемых портов я получаю:
GET http://localhost:8083/simdata net::ERR_CONNECTION_REFUSED
Вот создание C++ сервер:
Код: Выделить всё
#define WIN32_LEAN_AND_MEAN
#include
#include
#include "SimConnect.h"
#include
#include
#pragma comment(lib, "Ws2_32.lib")
HANDLE hSimConnect = NULL;
enum EVENT_ID {
EVENT_SIM_START,
EVENT_SIM_STOP,
EVENT_ENGINE_START,
EVENT_ENGINE_STOP,
};
enum DATA_REQUEST_ID {
DATA_REQUEST_ID,
};
struct PositionStruct {
double latitude;
double longitude;
double altitude;
};
struct AircraftDataStruct {
bool isEngineRunning;
bool isOnGround;
PositionStruct position;
bool engineCombustion[2];
};
AircraftDataStruct g_aircraftData = {
false,
false,
{0.0, 0.0, 0.0},
{false, false}
};
bool g_dataUpdated = false;
// Define standard ports to try
const int STANDARD_PORTS[] = { 8080, 8081, 8082, 8083, 8084 };
const int NUM_STANDARD_PORTS = sizeof(STANDARD_PORTS) / sizeof(STANDARD_PORTS[0]);
void CALLBACK SimConnectDispatchCallback(SIMCONNECT_RECV* pData, DWORD cbData, void* pContext)
{
switch (pData->dwID)
{
case SIMCONNECT_RECV_ID_SIMOBJECT_DATA:
{
SIMCONNECT_RECV_SIMOBJECT_DATA* pObjData = (SIMCONNECT_RECV_SIMOBJECT_DATA*)pData;
if (pObjData->dwRequestID == DATA_REQUEST_ID)
{
if (pObjData->dwDefineID == DATA_REQUEST_ID)
{
g_aircraftData.isOnGround = *(DWORD*)&pObjData->dwData;
g_aircraftData.position.latitude = *(double*)((char*)&pObjData->dwData + sizeof(DWORD));
g_aircraftData.position.longitude = *(double*)((char*)&pObjData->dwData + sizeof(DWORD) + sizeof(double));
g_aircraftData.position.altitude = *(double*)((char*)&pObjData->dwData + sizeof(DWORD) + sizeof(double) * 2);
g_aircraftData.engineCombustion[0] = *(DWORD*)((char*)&pObjData->dwData + sizeof(DWORD) + sizeof(double) * 3);
g_aircraftData.engineCombustion[1] = *(DWORD*)((char*)&pObjData->dwData + sizeof(DWORD) + sizeof(double) * 3 + sizeof(DWORD));
g_aircraftData.isEngineRunning = (g_aircraftData.engineCombustion[0] || g_aircraftData.engineCombustion[1]);
g_dataUpdated = true;
}
else
{
}
}
break;
}
default:
break;
}
}
void InitSimConnect()
{
HRESULT hr;
if (SUCCEEDED(SimConnect_Open(&hSimConnect, "SimBridge", NULL, 0, 0, 0)))
{
hr = SimConnect_AddToDataDefinition(hSimConnect, DATA_REQUEST_ID, "SIM ON GROUND", "Bool", SIMCONNECT_DATATYPE_INT32);
hr = SimConnect_AddToDataDefinition(hSimConnect, DATA_REQUEST_ID, "PLANE LATITUDE", "Degrees", SIMCONNECT_DATATYPE_FLOAT64);
hr = SimConnect_AddToDataDefinition(hSimConnect, DATA_REQUEST_ID, "PLANE LONGITUDE", "Degrees", SIMCONNECT_DATATYPE_FLOAT64);
hr = SimConnect_AddToDataDefinition(hSimConnect, DATA_REQUEST_ID, "PLANE ALTITUDE", "Feet", SIMCONNECT_DATATYPE_FLOAT64);
hr = SimConnect_AddToDataDefinition(hSimConnect, DATA_REQUEST_ID, "GENERAL ENG COMBUSTION:1", "Bool", SIMCONNECT_DATATYPE_INT32);
hr = SimConnect_AddToDataDefinition(hSimConnect, DATA_REQUEST_ID, "GENERAL ENG COMBUSTION:2", "Bool", SIMCONNECT_DATATYPE_INT32);
hr = SimConnect_RequestDataOnSimObject(hSimConnect, DATA_REQUEST_ID, DATA_REQUEST_ID, SIMCONNECT_OBJECT_ID_USER, SIMCONNECT_PERIOD_SECOND);
}
else
{
}
}
DWORD WINAPI HttpServerThread(LPVOID lpParam)
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
return 1;
}
SOCKET listenSocket = INVALID_SOCKET;
int portIndex = 0;
bool socketCreated = false;
while (!socketCreated && portIndex < NUM_STANDARD_PORTS)
{
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
WSACleanup();
return 1;
}
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
service.sin_port = htons(STANDARD_PORTS[portIndex]);
if (bind(listenSocket, reinterpret_cast(&service), sizeof(service)) != SOCKET_ERROR)
{
socketCreated = true;
}
else
{
closesocket(listenSocket);
portIndex++;
}
}
if (!socketCreated)
{
WSACleanup();
return 1;
}
if (listen(listenSocket, SOMAXCONN) == SOCKET_ERROR)
{
closesocket(listenSocket);
WSACleanup();
return 1;
}
while (true)
{
SOCKET clientSocket = accept(listenSocket, NULL, NULL);
if (clientSocket == INVALID_SOCKET)
{
closesocket(listenSocket);
WSACleanup();
return 1;
}
char recvbuf[512];
int recvbuflen = 512;
int bytesReceived = recv(clientSocket, recvbuf, recvbuflen, 0);
if (bytesReceived == SOCKET_ERROR)
{
closesocket(clientSocket);
continue;
}
std::string jsonResponse = "{";
jsonResponse += "\"isEngineRunning\": " + std::string(g_aircraftData.isEngineRunning ? "true" : "false") + ",";
jsonResponse += "\"isOnGround\": " + std::string(g_aircraftData.isOnGround ? "true" : "false") + ",";
jsonResponse += "\"position\": {\"latitude\": " + std::to_string(g_aircraftData.position.latitude) + ",";
jsonResponse += "\"longitude\": " + std::to_string(g_aircraftData.position.longitude) + ",";
jsonResponse += "\"altitude\": " + std::to_string(g_aircraftData.position.altitude) + "}";
jsonResponse += "}";
std::string httpResponse = "HTTP/1.1 200 OK\r\n";
httpResponse += "Content-Type: application/json\r\n";
httpResponse += "Content-Length: " + std::to_string(jsonResponse.length()) + "\r\n";
httpResponse += "Access-Control-Allow-Origin: *\r\n"; // Allow any origin
httpResponse += "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n";
httpResponse += "Access-Control-Allow-Headers: Content-Type\r\n";
httpResponse += "\r\n";
httpResponse += jsonResponse;
send(clientSocket, httpResponse.c_str(), static_cast(httpResponse.length()), 0);
closesocket(clientSocket);
}
closesocket(listenSocket);
WSACleanup();
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
InitSimConnect();
HANDLE hThread = CreateThread(NULL, 0, HttpServerThread, NULL, 0, NULL);
if (hThread == NULL)
{
return 1;
}
while (true)
{
SimConnect_CallDispatch(hSimConnect, SimConnectDispatchCallback, NULL);
// Check if data has been updated
if (g_dataUpdated)
{
g_dataUpdated = false;
}
Sleep(1000);
}
return 0;
}
Код: Выделить всё
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
const ports = [8080, 8081, 8082, 8083, 8084];
interface SimDataContextProps {
data: any;
error: string | null;
refreshData: () => void;
}
interface SimDataProviderProps {
children: ReactNode;
}
const SimDataContext = createContext(undefined);
export const SimDataProvider: React.FC = ({ children }) => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const fetchSimData = async () => {
for (let port of ports) {
try {
console.log(`Trying to fetch data from http://localhost:${port}/simdata`);
const response = await fetch(`http://localhost:${port}/simdata`);
if (response.ok) {
const jsonData = await response.json();
console.log(`Successfully fetched data from port ${port}:`, jsonData);
setData(jsonData);
setError(null);
return;
} else {
console.error(`Network response was not ok for port ${port}`);
}
} catch (err) {
console.error(`Error fetching from port ${port}:`, err);
}
}
setError('Failed to fetch data from all ports.');
};
useEffect(() => {
fetchSimData();
}, []);
return (
{children}
);
};
export const useSimData = () => {
const context = useContext(SimDataContext);
if (context === undefined) {
throw new Error('useSimData must be used within a SimDataProvider');
}
return context;
};
Спасибо за помощь!
Подробнее здесь: https://stackoverflow.com/questions/787 ... lhost-http