Я запускаю реализацию серверной части C++ через сообщество Visual Studio и веб-страницу из VS Code (Live Server).
Это мой журнал из Chromebrowser
WebSocket еще не открыт. Сообщение не отправлено

Я думаю, что может быть проблема с локальным хостом

Вот мой код Javascript и код C++:
Код: Выделить всё
let socket = new WebSocket("ws://localhost:7000");
socket.addEventListener('open', (event) => {
console.log('WebSocket connection opened. Ready state:', socket.readyState);
sendMessage();
});
socket.addEventListener('message', (event) => {
let chatOutput = document.getElementById('chat-output');
chatOutput.innerHTML += '' + event.data + '
';
});
socket.addEventListener('error', (error) => {
console.error('WebSocket error:', error);
});
socket.addEventListener('close', (event) => {
console.log('WebSocket connection closed. Code:', event.code, 'Reason:', event.reason);
});
function sendMessage() {
let chatInput = document.getElementById('chat-input');
let message = chatInput.value;
if (socket.readyState === WebSocket.OPEN) {
console.log('Sending message:', message);
socket.send(message);
chatInput.value = '';
} else {
console.log('WebSocket is not open yet. Message not sent.');
}
}
Код: Выделить всё
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
using boost::asio::ip::tcp;
class ChatSession : public std::enable_shared_from_this {
public:
ChatSession(tcp::socket socket) : socket_(std::move(socket)) {}
void Start() {
std::unique_lock lock(clientsMutex_); // Locking before modifying clients
clients_.push_back(shared_from_this());
Read();
}
private:
void Read() {
auto self(shared_from_this());
socket_.async_read_some(boost::asio::buffer(data_),
[this, self](const boost::system::error_code& error, std::size_t length) {
if (!error) {
std::wstring userMessage(data_.begin(), data_.begin() + length);
// Call ChatGPT API
std::wstring chatGPTResponse = chatWithGPT3(userMessage);
// Broadcast the ChatGPT response to all clients
Broadcast(chatGPTResponse);
Read(); // Continue reading.
}
else {
// Client disconnected, remove from clients vector.
std::unique_lock lock(clientsMutex_); // Locking before modifying clients_
clients_.erase(std::remove(clients_.begin(), clients_.end(), self), clients_.end());
}
});
}
void Broadcast(const std::wstring& message) {
for (auto& client : clients_) {
if (client != shared_from_this()) {
std::wstring messageToSend = L"ChatGPT: " + message;
boost::asio::write(client->socket_, boost::asio::buffer(messageToSend.data(), messageToSend.size()));
}
}
}
tcp::socket socket_;
std::array data_;
static std::vector clients_;
static std::mutex clientsMutex_;
std::wstring chatWithGPT3(const std::wstring& userMessage) {
const utility::string_t apiKey = U("Hiding my API key"); // ChatGPT API Key
web::http::client::http_client client(U("https://api.openai.com/v1/completions"));
web::http::http_request request(web::http::methods::POST);
request.headers().set_content_type(U("application/json"));
request.headers().add(U("Authorization"), U("Bearer ") + apiKey);
web::json::value body;
body[U("model")] = web::json::value::string(U("davinci-002"));
body[U("prompt")] = web::json::value::string(userMessage);
body[U("max_tokens")] = web::json::value(50); // Adjust as needed
request.set_body(body);
try {
web::http::http_response response = client.request(request).get();
if (response.status_code() == web::http::status_codes::OK) {
return response.to_string();
}
else {
std::cerr
Подробнее здесь: [url]https://stackoverflow.com/questions/77527360/i-am-having-a-issue-in-websocket-connection-between-client-and-server[/url]
Мобильная версия