Trying to make a Local Webpage were Multiple clients can chat with single Chatgpt bot.
I am running C++ Backend Implimentation through visual studio community and webpage from Vscode (Live Server).
This is my log from Chromebrowser
“WebSocket is not open yet. Message not sent. “

I think there might be issue with localhost

Here is my javascript code and c++ code,
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 += '<p>' + event.data + '</p>';
});
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 <iostream>
#include <vector>
#include <boost/asio.hpp>
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <cpprest/uri.h>
#include <mutex>
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<ChatSession> {
public:
ChatSession(tcp::socket socket) : socket_(std::move(socket)) {}
void Start() {
std::unique_lock<std::mutex> 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<std::mutex> 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<char, 1024> data_;
static std::vector<std::shared_ptr<ChatSession>> clients_;
static std::mutex clientsMutex_;
std::wstring chatWithGPT3(const std::wstring& userMessage) {
const utility::string_t apiKey = U("Hidding 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 << "ChatGPT API error: " << response.status_code() << std::endl;
std::cerr << "Response body: " << utility::conversions::to_utf8string(response.to_string()) << std::endl;
return L"An error occurred while processing your request.";
}
}
catch (const std::exception& e) {
std::cerr << "Exception in ChatGPT API request: " << e.what() << std::endl;
return L"An error occurred while processing your request.";
}
}
};
std::vector<std::shared_ptr<ChatSession>> ChatSession::clients_;
std::mutex ChatSession::clientsMutex_;
class ChatServer {
public:
ChatServer(boost::asio::io_context& io_context, short port)
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) {
Accept();
}
private:
void Accept() {
acceptor_.async_accept(
[this](const boost::system::error_code& error, tcp::socket socket) {
if (!error) {
auto session = std::make_shared<ChatSession>(std::move(socket));
session->Start();
}
Accept();
});
}
tcp::acceptor acceptor_;
};
int main() {
try {
boost::asio::io_context io_context;
ChatServer server(io_context, 7000); // Port
io_context.run();
}
catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
I tried Turning off my firewall but it made no difference.
I am expecting to be able to send message from webpage to Chatgpt.