Refactor Steam Networking Components
- Removed SteamMessageHandler class and its implementation files. - Integrated control packet handling directly into the SteamMessageHandler. - Updated TCPClient and TCPServer classes to improve connection management and error handling. - Added SteamNetworkingManager class to manage Steam networking, including lobby creation and connection handling. - Implemented callbacks for Steam Friends and Matchmaking to handle lobby events. - Enhanced message forwarding logic between TCP clients and Steam connections. - Introduced control packet handling for ping responses. - Improved thread safety with mutexes for shared resources.
This commit is contained in:
19
steamnet/control_packets.cpp
Normal file
19
steamnet/control_packets.cpp
Normal file
@@ -0,0 +1,19 @@
|
||||
#include "control_packets.h"
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
|
||||
// 假设需要访问全局变量,但为了简单,这里只打印
|
||||
// 如果需要,可以传递引用或使用全局
|
||||
|
||||
void handleControlPacket(const char* data, size_t size, HSteamNetConnection conn) {
|
||||
std::string_view packetData(data, size);
|
||||
std::cout << "Received control packet: " << packetData << " from connection " << conn << std::endl;
|
||||
// 这里添加处理逻辑,例如解析JSON或命令
|
||||
// 例如,如果data是"ping",回复"pong"
|
||||
if (packetData == "ping") {
|
||||
// 发送回复,但需要接口
|
||||
// 暂时只打印
|
||||
std::cout << "Responding to ping" << std::endl;
|
||||
}
|
||||
// 可以扩展为更多控制命令
|
||||
}
|
||||
8
steamnet/control_packets.h
Normal file
8
steamnet/control_packets.h
Normal file
@@ -0,0 +1,8 @@
|
||||
#ifndef CONTROL_PACKETS_H
|
||||
#define CONTROL_PACKETS_H
|
||||
|
||||
#include <steamnetworkingtypes.h>
|
||||
|
||||
void handleControlPacket(const char* data, size_t size, HSteamNetConnection conn);
|
||||
|
||||
#endif // CONTROL_PACKETS_H
|
||||
108
steamnet/steam_message_handler.cpp
Normal file
108
steamnet/steam_message_handler.cpp
Normal file
@@ -0,0 +1,108 @@
|
||||
#include "steam_message_handler.h"
|
||||
#include <iostream>
|
||||
#include <cstring>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <steam_api.h>
|
||||
#include <isteamnetworkingsockets.h>
|
||||
|
||||
// Constants for control packets
|
||||
const char* CONTROL_PREFIX = "CONTROL:";
|
||||
const size_t CONTROL_PREFIX_LEN = 8;
|
||||
|
||||
SteamMessageHandler::SteamMessageHandler(boost::asio::io_context& io_context, ISteamNetworkingSockets* interface, std::vector<HSteamNetConnection>& connections, std::map<HSteamNetConnection, std::shared_ptr<TCPClient>>& clientMap, std::mutex& clientMutex, std::mutex& connectionsMutex, std::unique_ptr<TCPServer>& server, bool& g_isHost, int& localPort)
|
||||
: io_context_(io_context), m_pInterface_(interface), connections_(connections), clientMap_(clientMap), clientMutex_(clientMutex), connectionsMutex_(connectionsMutex), server_(server), g_isHost_(g_isHost), localPort_(localPort), running_(false) {}
|
||||
|
||||
SteamMessageHandler::~SteamMessageHandler() {
|
||||
stop();
|
||||
}
|
||||
|
||||
void SteamMessageHandler::handleControlPacket(const char* data, size_t size, HSteamNetConnection conn) {
|
||||
std::string_view packetData(data, size);
|
||||
std::cout << "Received control packet: " << packetData << " from connection " << conn << std::endl;
|
||||
// Add handling logic here
|
||||
if (packetData == "ping") {
|
||||
std::cout << "Responding to ping" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void SteamMessageHandler::start() {
|
||||
if (running_) return;
|
||||
running_ = true;
|
||||
thread_ = std::thread([this]() { run(); });
|
||||
}
|
||||
|
||||
void SteamMessageHandler::stop() {
|
||||
if (!running_) return;
|
||||
running_ = false;
|
||||
if (thread_.joinable()) {
|
||||
thread_.join();
|
||||
}
|
||||
}
|
||||
|
||||
void SteamMessageHandler::run() {
|
||||
while (running_) {
|
||||
// Poll networking
|
||||
m_pInterface_->RunCallbacks();
|
||||
|
||||
// Update user info (assuming userMap is accessible, but for simplicity, skip or add as param)
|
||||
// Note: userMap update might need to be handled elsewhere or passed
|
||||
|
||||
// Receive messages
|
||||
pollMessages();
|
||||
|
||||
// Sleep a bit to avoid busy loop
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
}
|
||||
|
||||
void SteamMessageHandler::pollMessages() {
|
||||
std::vector<HSteamNetConnection> currentConnections;
|
||||
{
|
||||
std::lock_guard<std::mutex> lockConn(connectionsMutex_);
|
||||
currentConnections = connections_;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(clientMutex_);
|
||||
for (auto conn : currentConnections) {
|
||||
ISteamNetworkingMessage* pIncomingMsgs[10];
|
||||
int numMsgs = m_pInterface_->ReceiveMessagesOnConnection(conn, pIncomingMsgs, 10);
|
||||
for (int i = 0; i < numMsgs; ++i) {
|
||||
ISteamNetworkingMessage* pIncomingMsg = pIncomingMsgs[i];
|
||||
const char* data = (const char*)pIncomingMsg->m_pData;
|
||||
size_t size = pIncomingMsg->m_cbSize;
|
||||
if (size >= CONTROL_PREFIX_LEN && memcmp(data, CONTROL_PREFIX, CONTROL_PREFIX_LEN) == 0) {
|
||||
// Handle control packet
|
||||
handleControlPacket(data + CONTROL_PREFIX_LEN, size - CONTROL_PREFIX_LEN, conn);
|
||||
} else {
|
||||
// Normal forwarding
|
||||
if (server_) {
|
||||
server_->sendToAll((const char*)pIncomingMsg->m_pData, pIncomingMsg->m_cbSize);
|
||||
}
|
||||
// Lazy connect: Create TCP Client on first message if not already connected
|
||||
if (clientMap_.find(conn) == clientMap_.end() && g_isHost_ && localPort_ > 0) {
|
||||
auto client = std::make_shared<TCPClient>("localhost", localPort_);
|
||||
if (client->connect()) {
|
||||
client->setReceiveCallback([conn, this](const char* data, size_t size) {
|
||||
std::lock_guard<std::mutex> lock(clientMutex_);
|
||||
m_pInterface_->SendMessageToConnection(conn, data, size, k_nSteamNetworkingSend_Reliable, nullptr);
|
||||
});
|
||||
client->setDisconnectCallback([conn, this]() {
|
||||
std::lock_guard<std::mutex> lock(clientMutex_);
|
||||
if (clientMap_.count(conn)) {
|
||||
clientMap_[conn]->disconnect();
|
||||
clientMap_.erase(conn);
|
||||
std::cout << "TCP client disconnected, removed from map" << std::endl;
|
||||
}
|
||||
});
|
||||
clientMap_[conn] = client;
|
||||
std::cout << "Created TCP Client for connection on first message" << std::endl;
|
||||
} else {
|
||||
std::cerr << "Failed to connect TCP Client for connection" << std::endl;
|
||||
}
|
||||
}
|
||||
// Send to corresponding TCP client if exists (for host)
|
||||
}
|
||||
pIncomingMsg->Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
42
steamnet/steam_message_handler.h
Normal file
42
steamnet/steam_message_handler.h
Normal file
@@ -0,0 +1,42 @@
|
||||
#ifndef STEAM_MESSAGE_HANDLER_H
|
||||
#define STEAM_MESSAGE_HANDLER_H
|
||||
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <memory>
|
||||
#include <boost/asio.hpp>
|
||||
#include <steamnetworkingtypes.h>
|
||||
#include "tcp_server.h"
|
||||
#include "tcp/tcp_client.h"
|
||||
#include "control_packets.h"
|
||||
|
||||
class SteamMessageHandler {
|
||||
public:
|
||||
SteamMessageHandler(boost::asio::io_context& io_context, ISteamNetworkingSockets* interface, std::vector<HSteamNetConnection>& connections, std::map<HSteamNetConnection, std::shared_ptr<TCPClient>>& clientMap, std::mutex& clientMutex, std::mutex& connectionsMutex, std::unique_ptr<TCPServer>& server, bool& g_isHost, int& localPort);
|
||||
~SteamMessageHandler();
|
||||
|
||||
void start();
|
||||
void stop();
|
||||
|
||||
private:
|
||||
void run();
|
||||
void pollMessages();
|
||||
void handleControlPacket(const char* data, size_t size, HSteamNetConnection conn);
|
||||
|
||||
boost::asio::io_context& io_context_;
|
||||
ISteamNetworkingSockets* m_pInterface_;
|
||||
std::vector<HSteamNetConnection>& connections_;
|
||||
std::map<HSteamNetConnection, std::shared_ptr<TCPClient>>& clientMap_;
|
||||
std::mutex& clientMutex_;
|
||||
std::mutex& connectionsMutex_;
|
||||
std::unique_ptr<TCPServer>& server_;
|
||||
bool& g_isHost_;
|
||||
int& localPort_;
|
||||
|
||||
std::thread thread_;
|
||||
bool running_;
|
||||
};
|
||||
|
||||
#endif // STEAM_MESSAGE_HANDLER_H
|
||||
292
steamnet/steam_networking_manager.cpp
Normal file
292
steamnet/steam_networking_manager.cpp
Normal file
@@ -0,0 +1,292 @@
|
||||
#include "steam_networking_manager.h"
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
|
||||
SteamNetworkingManager* SteamNetworkingManager::instance = nullptr;
|
||||
|
||||
// Static callback function
|
||||
void SteamNetworkingManager::OnSteamNetConnectionStatusChanged(SteamNetConnectionStatusChangedCallback_t *pInfo) {
|
||||
if (instance) {
|
||||
instance->handleConnectionStatusChanged(pInfo);
|
||||
}
|
||||
}
|
||||
|
||||
SteamFriendsCallbacks::SteamFriendsCallbacks(SteamNetworkingManager* manager) : manager_(manager) {}
|
||||
|
||||
void SteamFriendsCallbacks::OnGameRichPresenceJoinRequested(GameRichPresenceJoinRequested_t *pCallback) {
|
||||
if (manager_) {
|
||||
const char* connectStr = SteamFriends()->GetFriendRichPresence(pCallback->m_steamIDFriend, "connect");
|
||||
if (connectStr && connectStr[0] != '\0') {
|
||||
uint64 lobbyID = std::stoull(connectStr);
|
||||
CSteamID lobbySteamID(lobbyID);
|
||||
if (!manager_->isHost() && !manager_->isConnected()) {
|
||||
manager_->joinLobby(lobbySteamID);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SteamNetworkingManager::SteamNetworkingManager()
|
||||
: m_pInterface(nullptr), hListenSock(k_HSteamListenSocket_Invalid), g_isHost(false), g_isClient(false), g_isConnected(false),
|
||||
g_hConnection(k_HSteamNetConnection_Invalid), g_retryCount(0), g_currentVirtualPort(0),
|
||||
io_context_(nullptr), clientMap_(nullptr), clientMutex_(nullptr), server_(nullptr), localPort_(nullptr), messageHandler_(nullptr),
|
||||
steamFriendsCallbacks(this), steamMatchmakingCallbacks(this), currentLobby(k_steamIDNil) {
|
||||
// Initialize connection config
|
||||
g_connectionConfig[0].SetInt32(k_ESteamNetworkingConfig_TimeoutInitial, 10000);
|
||||
g_connectionConfig[1].SetInt32(k_ESteamNetworkingConfig_NagleTime, 0);
|
||||
}
|
||||
|
||||
SteamNetworkingManager::~SteamNetworkingManager() {
|
||||
stopMessageHandler();
|
||||
delete messageHandler_;
|
||||
shutdown();
|
||||
}
|
||||
|
||||
bool SteamNetworkingManager::initialize() {
|
||||
instance = this;
|
||||
if (!SteamAPI_Init()) {
|
||||
std::cerr << "Failed to initialize Steam API" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
SteamNetworkingUtils()->InitRelayNetworkAccess();
|
||||
SteamNetworkingUtils()->SetGlobalCallback_SteamNetConnectionStatusChanged(OnSteamNetConnectionStatusChanged);
|
||||
|
||||
m_pInterface = SteamNetworkingSockets();
|
||||
|
||||
// Get friends list
|
||||
int friendCount = SteamFriends()->GetFriendCount(k_EFriendFlagAll);
|
||||
for (int i = 0; i < friendCount; ++i) {
|
||||
CSteamID friendID = SteamFriends()->GetFriendByIndex(i, k_EFriendFlagAll);
|
||||
const char* name = SteamFriends()->GetFriendPersonaName(friendID);
|
||||
friendsList.push_back({friendID, name});
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void SteamNetworkingManager::shutdown() {
|
||||
leaveLobby();
|
||||
if (g_hConnection != k_HSteamNetConnection_Invalid) {
|
||||
m_pInterface->CloseConnection(g_hConnection, 0, nullptr, false);
|
||||
}
|
||||
if (hListenSock != k_HSteamListenSocket_Invalid) {
|
||||
m_pInterface->CloseListenSocket(hListenSock);
|
||||
}
|
||||
SteamAPI_Shutdown();
|
||||
}
|
||||
|
||||
bool SteamNetworkingManager::createLobby() {
|
||||
SteamAPICall_t hSteamAPICall = SteamMatchmaking()->CreateLobby(k_ELobbyTypePublic, 4);
|
||||
if (hSteamAPICall == k_uAPICallInvalid) {
|
||||
std::cerr << "Failed to create lobby" << std::endl;
|
||||
return false;
|
||||
}
|
||||
// Call result will be handled by callback
|
||||
return true;
|
||||
}
|
||||
|
||||
void SteamNetworkingManager::leaveLobby() {
|
||||
if (currentLobby != k_steamIDNil) {
|
||||
SteamMatchmaking()->LeaveLobby(currentLobby);
|
||||
currentLobby = k_steamIDNil;
|
||||
}
|
||||
}
|
||||
|
||||
bool SteamNetworkingManager::searchLobbies() {
|
||||
lobbies.clear();
|
||||
SteamAPICall_t hSteamAPICall = SteamMatchmaking()->RequestLobbyList();
|
||||
if (hSteamAPICall == k_uAPICallInvalid) {
|
||||
std::cerr << "Failed to request lobby list" << std::endl;
|
||||
return false;
|
||||
}
|
||||
// Results will be handled by callback
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SteamNetworkingManager::joinLobby(CSteamID lobbyID) {
|
||||
if (SteamMatchmaking()->JoinLobby(lobbyID) != k_EResultOK) {
|
||||
std::cerr << "Failed to join lobby" << std::endl;
|
||||
return false;
|
||||
}
|
||||
// Connection will be handled by callback
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SteamNetworkingManager::startHosting() {
|
||||
if (!createLobby()) {
|
||||
return false;
|
||||
}
|
||||
hListenSock = m_pInterface->CreateListenSocketP2P(0, 0, nullptr);
|
||||
if (hListenSock != k_HSteamListenSocket_Invalid) {
|
||||
g_isHost = true;
|
||||
std::cout << "Created listen socket for hosting game room" << std::endl;
|
||||
// Rich Presence is set in OnLobbyCreated callback
|
||||
return true;
|
||||
} else {
|
||||
std::cerr << "Failed to create listen socket for hosting" << std::endl;
|
||||
leaveLobby();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void SteamNetworkingManager::stopHosting() {
|
||||
if (hListenSock != k_HSteamListenSocket_Invalid) {
|
||||
m_pInterface->CloseListenSocket(hListenSock);
|
||||
hListenSock = k_HSteamListenSocket_Invalid;
|
||||
}
|
||||
leaveLobby();
|
||||
g_isHost = false;
|
||||
}
|
||||
|
||||
bool SteamNetworkingManager::joinHost(uint64 hostID) {
|
||||
CSteamID hostSteamID(hostID);
|
||||
g_isClient = true;
|
||||
g_hostSteamID = hostSteamID;
|
||||
g_retryCount = 0;
|
||||
g_currentVirtualPort = 0;
|
||||
SteamNetworkingIdentity identity;
|
||||
identity.SetSteamID(hostSteamID);
|
||||
g_hConnection = m_pInterface->ConnectP2P(identity, g_currentVirtualPort, 2, g_connectionConfig);
|
||||
if (g_hConnection != k_HSteamNetConnection_Invalid) {
|
||||
std::cout << "Attempting to connect to host " << hostSteamID.ConvertToUint64() << " with virtual port " << g_currentVirtualPort << std::endl;
|
||||
return true;
|
||||
} else {
|
||||
std::cerr << "Failed to initiate connection" << std::endl;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void SteamNetworkingManager::setMessageHandlerDependencies(boost::asio::io_context& io_context, std::map<HSteamNetConnection, std::shared_ptr<TCPClient>>& clientMap, std::mutex& clientMutex, std::unique_ptr<TCPServer>& server, int& localPort) {
|
||||
io_context_ = &io_context;
|
||||
clientMap_ = &clientMap;
|
||||
clientMutex_ = &clientMutex;
|
||||
server_ = &server;
|
||||
localPort_ = &localPort;
|
||||
messageHandler_ = new SteamMessageHandler(io_context, m_pInterface, connections, clientMap, clientMutex, connectionsMutex, server, g_isHost, localPort);
|
||||
}
|
||||
|
||||
void SteamNetworkingManager::startMessageHandler() {
|
||||
if (messageHandler_) {
|
||||
messageHandler_->start();
|
||||
}
|
||||
}
|
||||
|
||||
void SteamNetworkingManager::stopMessageHandler() {
|
||||
if (messageHandler_) {
|
||||
messageHandler_->stop();
|
||||
}
|
||||
}
|
||||
|
||||
void SteamNetworkingManager::handleConnectionStatusChanged(SteamNetConnectionStatusChangedCallback_t *pInfo) {
|
||||
std::lock_guard<std::mutex> lock(connectionsMutex);
|
||||
std::cout << "Connection status changed: " << pInfo->m_info.m_eState << " for connection " << pInfo->m_hConn << std::endl;
|
||||
if (pInfo->m_info.m_eState == k_ESteamNetworkingConnectionState_ProblemDetectedLocally) {
|
||||
std::cout << "Connection failed: " << pInfo->m_info.m_szEndDebug << std::endl;
|
||||
}
|
||||
if (pInfo->m_eOldState == k_ESteamNetworkingConnectionState_None && pInfo->m_info.m_eState == k_ESteamNetworkingConnectionState_Connecting) {
|
||||
m_pInterface->AcceptConnection(pInfo->m_hConn);
|
||||
connections.push_back(pInfo->m_hConn);
|
||||
g_hConnection = pInfo->m_hConn;
|
||||
g_isConnected = true;
|
||||
std::cout << "Accepted incoming connection from " << pInfo->m_info.m_identityRemote.GetSteamID().ConvertToUint64() << std::endl;
|
||||
// Add user info
|
||||
SteamNetConnectionInfo_t info;
|
||||
SteamNetConnectionRealTimeStatus_t status;
|
||||
if (m_pInterface->GetConnectionInfo(pInfo->m_hConn, &info) && m_pInterface->GetConnectionRealTimeStatus(pInfo->m_hConn, &status, 0, nullptr)) {
|
||||
UserInfo userInfo;
|
||||
userInfo.steamID = pInfo->m_info.m_identityRemote.GetSteamID();
|
||||
userInfo.name = SteamFriends()->GetFriendPersonaName(userInfo.steamID);
|
||||
userInfo.ping = status.m_nPing;
|
||||
userInfo.isRelay = (info.m_idPOPRelay != 0);
|
||||
userMap[pInfo->m_hConn] = userInfo;
|
||||
std::cout << "Incoming connection details: ping=" << status.m_nPing << "ms, relay=" << (info.m_idPOPRelay != 0 ? "yes" : "no") << std::endl;
|
||||
}
|
||||
} else if (pInfo->m_eOldState == k_ESteamNetworkingConnectionState_Connecting && pInfo->m_info.m_eState == k_ESteamNetworkingConnectionState_Connected) {
|
||||
g_isConnected = true;
|
||||
std::cout << "Connected to host" << std::endl;
|
||||
// Add user info
|
||||
SteamNetConnectionInfo_t info;
|
||||
SteamNetConnectionRealTimeStatus_t status;
|
||||
if (m_pInterface->GetConnectionInfo(pInfo->m_hConn, &info) && m_pInterface->GetConnectionRealTimeStatus(pInfo->m_hConn, &status, 0, nullptr)) {
|
||||
UserInfo userInfo;
|
||||
userInfo.steamID = pInfo->m_info.m_identityRemote.GetSteamID();
|
||||
userInfo.name = SteamFriends()->GetFriendPersonaName(userInfo.steamID);
|
||||
userInfo.ping = status.m_nPing;
|
||||
userInfo.isRelay = (info.m_idPOPRelay != 0);
|
||||
userMap[pInfo->m_hConn] = userInfo;
|
||||
std::cout << "Outgoing connection details: ping=" << status.m_nPing << "ms, relay=" << (info.m_idPOPRelay != 0 ? "yes" : "no") << std::endl;
|
||||
}
|
||||
} else if (pInfo->m_info.m_eState == k_ESteamNetworkingConnectionState_ClosedByPeer || pInfo->m_info.m_eState == k_ESteamNetworkingConnectionState_ProblemDetectedLocally) {
|
||||
g_isConnected = false;
|
||||
g_hConnection = k_HSteamNetConnection_Invalid;
|
||||
// Remove from connections
|
||||
auto it = std::find(connections.begin(), connections.end(), pInfo->m_hConn);
|
||||
if (it != connections.end()) {
|
||||
connections.erase(it);
|
||||
}
|
||||
userMap.erase(pInfo->m_hConn);
|
||||
std::cout << "Connection closed" << std::endl;
|
||||
|
||||
// Retry if client
|
||||
if (g_isClient && !g_isConnected && g_retryCount < MAX_RETRIES) {
|
||||
g_retryCount++;
|
||||
g_currentVirtualPort++;
|
||||
SteamNetworkingIdentity identity;
|
||||
identity.SetSteamID(g_hostSteamID);
|
||||
HSteamNetConnection newConn = m_pInterface->ConnectP2P(identity, g_currentVirtualPort, 2, g_connectionConfig);
|
||||
if (newConn != k_HSteamNetConnection_Invalid) {
|
||||
g_hConnection = newConn;
|
||||
std::cout << "Retrying connection attempt " << g_retryCount << " with virtual port " << g_currentVirtualPort << std::endl;
|
||||
} else {
|
||||
std::cerr << "Failed to initiate retry connection" << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SteamMatchmakingCallbacks::SteamMatchmakingCallbacks(SteamNetworkingManager* manager) : manager_(manager) {}
|
||||
|
||||
void SteamMatchmakingCallbacks::OnLobbyCreated(LobbyCreated_t *pCallback) {
|
||||
if (pCallback->m_eResult == k_EResultOK) {
|
||||
manager_->currentLobby = pCallback->m_ulSteamIDLobby;
|
||||
std::cout << "Lobby created: " << manager_->currentLobby.ConvertToUint64() << std::endl;
|
||||
// Set Rich Presence with lobby ID
|
||||
std::string lobbyStr = std::to_string(manager_->currentLobby.ConvertToUint64());
|
||||
SteamFriends()->SetRichPresence("connect", lobbyStr.c_str());
|
||||
SteamFriends()->SetRichPresence("status", "主持游戏房间");
|
||||
} else {
|
||||
std::cerr << "Failed to create lobby" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void SteamMatchmakingCallbacks::OnLobbyListReceived(LobbyMatchList_t *pCallback) {
|
||||
manager_->lobbies.clear();
|
||||
for (uint32 i = 0; i < pCallback->m_nLobbiesMatching; ++i) {
|
||||
CSteamID lobbyID = SteamMatchmaking()->GetLobbyByIndex(i);
|
||||
manager_->lobbies.push_back(lobbyID);
|
||||
}
|
||||
std::cout << "Received " << pCallback->m_nLobbiesMatching << " lobbies" << std::endl;
|
||||
}
|
||||
|
||||
void SteamMatchmakingCallbacks::OnLobbyEntered(LobbyEnter_t *pCallback) {
|
||||
if (pCallback->m_EChatRoomEnterResponse == k_EChatRoomEnterResponseSuccess) {
|
||||
manager_->currentLobby = pCallback->m_ulSteamIDLobby;
|
||||
std::cout << "Entered lobby: " << pCallback->m_ulSteamIDLobby << std::endl;
|
||||
// Only join host if not the host
|
||||
if (!manager_->isHost()) {
|
||||
CSteamID hostID = SteamMatchmaking()->GetLobbyOwner(pCallback->m_ulSteamIDLobby);
|
||||
if (manager_->joinHost(hostID.ConvertToUint64())) {
|
||||
// Start TCP Server if dependencies are set
|
||||
if (manager_->server_ && !(*manager_->server_)) {
|
||||
*manager_->server_ = std::make_unique<TCPServer>(8888, manager_);
|
||||
if (!(*manager_->server_)->start()) {
|
||||
std::cerr << "Failed to start TCP server" << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::cerr << "Failed to enter lobby" << std::endl;
|
||||
}
|
||||
}
|
||||
141
steamnet/steam_networking_manager.h
Normal file
141
steamnet/steam_networking_manager.h
Normal file
@@ -0,0 +1,141 @@
|
||||
#ifndef STEAM_NETWORKING_MANAGER_H
|
||||
#define STEAM_NETWORKING_MANAGER_H
|
||||
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <steam_api.h>
|
||||
#include <isteamnetworkingsockets.h>
|
||||
#include <isteamnetworkingutils.h>
|
||||
#include <steamnetworkingtypes.h>
|
||||
#include <isteammatchmaking.h>
|
||||
#include "steam_message_handler.h"
|
||||
|
||||
// Forward declarations
|
||||
class TCPClient;
|
||||
class TCPServer;
|
||||
class SteamNetworkingManager;
|
||||
|
||||
// Callback class for Steam Friends
|
||||
class SteamFriendsCallbacks {
|
||||
public:
|
||||
SteamFriendsCallbacks(SteamNetworkingManager* manager);
|
||||
STEAM_CALLBACK(SteamFriendsCallbacks, OnGameRichPresenceJoinRequested, GameRichPresenceJoinRequested_t);
|
||||
private:
|
||||
SteamNetworkingManager* manager_;
|
||||
};
|
||||
|
||||
// Callback class for Steam Matchmaking
|
||||
class SteamMatchmakingCallbacks {
|
||||
public:
|
||||
SteamMatchmakingCallbacks(SteamNetworkingManager* manager);
|
||||
STEAM_CALLBACK(SteamMatchmakingCallbacks, OnLobbyCreated, LobbyCreated_t);
|
||||
STEAM_CALLBACK(SteamMatchmakingCallbacks, OnLobbyListReceived, LobbyMatchList_t);
|
||||
STEAM_CALLBACK(SteamMatchmakingCallbacks, OnLobbyEntered, LobbyEnter_t);
|
||||
private:
|
||||
SteamNetworkingManager* manager_;
|
||||
};
|
||||
|
||||
// User info structure
|
||||
struct UserInfo {
|
||||
CSteamID steamID;
|
||||
std::string name;
|
||||
int ping;
|
||||
bool isRelay;
|
||||
};
|
||||
|
||||
class SteamNetworkingManager {
|
||||
public:
|
||||
static SteamNetworkingManager* instance;
|
||||
SteamNetworkingManager();
|
||||
~SteamNetworkingManager();
|
||||
|
||||
bool initialize();
|
||||
void shutdown();
|
||||
|
||||
// Hosting
|
||||
bool startHosting();
|
||||
void stopHosting();
|
||||
|
||||
// Lobby
|
||||
bool createLobby();
|
||||
void leaveLobby();
|
||||
bool searchLobbies();
|
||||
bool joinLobby(CSteamID lobbyID);
|
||||
const std::vector<CSteamID>& getLobbies() const { return lobbies; }
|
||||
CSteamID getCurrentLobby() const { return currentLobby; }
|
||||
|
||||
// Joining
|
||||
bool joinHost(uint64 hostID);
|
||||
void disconnect();
|
||||
|
||||
// Getters
|
||||
bool isHost() const { return g_isHost; }
|
||||
bool isClient() const { return g_isClient; }
|
||||
bool isConnected() const { return g_isConnected; }
|
||||
const std::vector<std::pair<CSteamID, std::string>>& getFriendsList() const { return friendsList; }
|
||||
const std::map<HSteamNetConnection, UserInfo>& getUserMap() const { return userMap; }
|
||||
const std::vector<HSteamNetConnection>& getConnections() const { return connections; }
|
||||
HSteamNetConnection getConnection() const { return g_hConnection; }
|
||||
ISteamNetworkingSockets* getInterface() const { return m_pInterface; }
|
||||
|
||||
void setMessageHandlerDependencies(boost::asio::io_context& io_context, std::map<HSteamNetConnection, std::shared_ptr<TCPClient>>& clientMap, std::mutex& clientMutex, std::unique_ptr<TCPServer>& server, int& localPort);
|
||||
|
||||
// Message handler
|
||||
void startMessageHandler();
|
||||
void stopMessageHandler();
|
||||
|
||||
// For callbacks
|
||||
void setHostSteamID(CSteamID id) { g_hostSteamID = id; }
|
||||
CSteamID getHostSteamID() const { return g_hostSteamID; }
|
||||
|
||||
friend class SteamFriendsCallbacks;
|
||||
friend class SteamMatchmakingCallbacks;
|
||||
|
||||
private:
|
||||
// Steam API
|
||||
ISteamNetworkingSockets* m_pInterface;
|
||||
|
||||
// Hosting
|
||||
HSteamListenSocket hListenSock;
|
||||
bool g_isHost;
|
||||
bool g_isClient;
|
||||
bool g_isConnected;
|
||||
HSteamNetConnection g_hConnection;
|
||||
CSteamID g_hostSteamID;
|
||||
|
||||
// Lobby
|
||||
std::vector<CSteamID> lobbies;
|
||||
CSteamID currentLobby;
|
||||
|
||||
// Connections
|
||||
std::vector<HSteamNetConnection> connections;
|
||||
std::map<HSteamNetConnection, UserInfo> userMap;
|
||||
std::mutex connectionsMutex;
|
||||
|
||||
// Connection config
|
||||
SteamNetworkingConfigValue_t g_connectionConfig[2];
|
||||
int g_retryCount;
|
||||
const int MAX_RETRIES = 3;
|
||||
int g_currentVirtualPort;
|
||||
|
||||
// Friends
|
||||
std::vector<std::pair<CSteamID, std::string>> friendsList;
|
||||
SteamFriendsCallbacks steamFriendsCallbacks;
|
||||
SteamMatchmakingCallbacks steamMatchmakingCallbacks;
|
||||
|
||||
// Message handler dependencies
|
||||
boost::asio::io_context* io_context_;
|
||||
std::map<HSteamNetConnection, std::shared_ptr<TCPClient>>* clientMap_;
|
||||
std::mutex* clientMutex_;
|
||||
std::unique_ptr<TCPServer>* server_;
|
||||
int* localPort_;
|
||||
SteamMessageHandler* messageHandler_;
|
||||
|
||||
// Callback
|
||||
static void OnSteamNetConnectionStatusChanged(SteamNetConnectionStatusChangedCallback_t *pInfo);
|
||||
void handleConnectionStatusChanged(SteamNetConnectionStatusChangedCallback_t *pInfo);
|
||||
};
|
||||
|
||||
#endif // STEAM_NETWORKING_MANAGER_H
|
||||
Reference in New Issue
Block a user