add ws ping/pong.
All checks were successful
Deploy / Build (push) Successful in 5m54s

This commit is contained in:
amass 2025-01-15 15:24:47 +08:00
parent 9e8e847787
commit e3580ec8f4
6 changed files with 81 additions and 30 deletions

View File

@ -3,6 +3,7 @@
#include "StringUtility.h" #include "StringUtility.h"
#include <boost/json/parse.hpp> #include <boost/json/parse.hpp>
#include <boost/json/serialize.hpp> #include <boost/json/serialize.hpp>
#include <boost/scope/scope_exit.hpp>
WebSocketSignalSession::WebSocketSignalSession(boost::asio::ip::tcp::socket &&socket, SignalServer &server, const std::string &id) WebSocketSignalSession::WebSocketSignalSession(boost::asio::ip::tcp::socket &&socket, SignalServer &server, const std::string &id)
: m_ws(std::move(socket)), m_server(server), m_id(id) { : m_ws(std::move(socket)), m_server(server), m_id(id) {
@ -31,8 +32,16 @@ void WebSocketSignalSession::onRead(const boost::beast::error_code &error, std::
LOG(error) << error << ": " << error.message(); LOG(error) << error << ": " << error.message();
return; return;
} }
boost::scope::scope_exit raii([this] {
m_buffer.consume(m_buffer.size()); // Clear the buffer
m_ws.async_read(m_buffer, boost::beast::bind_front_handler(&WebSocketSignalSession::onRead, shared_from_this()));
});
if (!m_ws.got_text()) {
LOG(warning) << "current not supported binary message.";
return;
}
auto message = boost::beast::buffers_to_string(m_buffer.data()); auto message = boost::beast::buffers_to_string(m_buffer.data());
LOG(info) << message;
auto rootObject = boost::json::parse(message); auto rootObject = boost::json::parse(message);
auto &root = rootObject.as_object(); auto &root = rootObject.as_object();
if (root.contains("id")) { if (root.contains("id")) {
@ -50,31 +59,36 @@ void WebSocketSignalSession::onRead(const boost::beast::error_code &error, std::
auto reply = std::make_shared<std::string>(boost::json::serialize(root)); auto reply = std::make_shared<std::string>(boost::json::serialize(root));
destination->send(reply); destination->send(reply);
} }
LOG(info) << message;
} else if (root.contains("type")) {
auto &type = root.at("type").as_string();
if (type == "ping") {
boost::json::object object;
object["type"] = "pong";
send(boost::json::serialize(object));
}
} else {
LOG(info) << message;
} }
m_buffer.consume(m_buffer.size()); // Clear the buffer
m_ws.async_read(m_buffer, boost::beast::bind_front_handler(&WebSocketSignalSession::onRead, shared_from_this()));
} }
void WebSocketSignalSession::send(std::shared_ptr<std::string const> const &ss) { void WebSocketSignalSession::send(const std::shared_ptr<std::string> &ss) {
m_ws.text(); boost::asio::post(m_ws.get_executor(), [ptr = weak_from_this(), ss]() {
boost::asio::post(m_ws.get_executor(), if (ptr.expired()) return;
boost::beast::bind_front_handler(&WebSocketSignalSession::onSend, shared_from_this(), ss)); auto self = ptr.lock();
self->m_queue.push_back(ss);
if (self->m_queue.size() > 1) return; // 之前已经有发送了
self->m_ws.text();
self->m_ws.async_write(boost::asio::buffer(*self->m_queue.front()),
boost::beast::bind_front_handler(&WebSocketSignalSession::on_write, self->shared_from_this()));
});
} }
void WebSocketSignalSession::onSend(std::shared_ptr<std::string const> const &ss) { void WebSocketSignalSession::send(std::string &&message) {
// Always add to queue return send(std::make_shared<std::string>(std::move(message)));
m_queue.push_back(ss);
// Are we already writing?
if (m_queue.size() > 1) return;
// We are not currently writing, so send this immediately
m_ws.async_write(boost::asio::buffer(*m_queue.front()),
boost::beast::bind_front_handler(&WebSocketSignalSession::on_write, shared_from_this()));
} }
void WebSocketSignalSession::on_write(boost::beast::error_code ec, std::size_t) { void WebSocketSignalSession::on_write(boost::beast::error_code ec, std::size_t) {
// Handle the error, if any
if (ec) { if (ec) {
// Don't report these // Don't report these
if (ec == boost::asio::error::operation_aborted || ec == boost::beast::websocket::error::closed) return; if (ec == boost::asio::error::operation_aborted || ec == boost::beast::websocket::error::closed) return;

View File

@ -36,13 +36,13 @@ public:
} }
// Send a message // Send a message
void send(std::shared_ptr<std::string const> const &ss); void send(const std::shared_ptr<std::string> &ss);
void send(std::string &&message);
protected: protected:
void onAccept(boost::beast::error_code ec); void onAccept(boost::beast::error_code ec);
void onRead(const boost::beast::error_code &error, std::size_t bytesTransferred); void onRead(const boost::beast::error_code &error, std::size_t bytesTransferred);
void on_write(boost::beast::error_code ec, std::size_t bytes_transferred); void on_write(boost::beast::error_code ec, std::size_t bytes_transferred);
void onSend(std::shared_ptr<std::string const> const &ss);
private: private:
boost::beast::websocket::stream<boost::beast::tcp_stream> m_ws; boost::beast::websocket::stream<boost::beast::tcp_stream> m_ws;
@ -50,7 +50,7 @@ private:
std::string m_id; std::string m_id;
std::string m_target; std::string m_target;
boost::beast::flat_buffer m_buffer; boost::beast::flat_buffer m_buffer;
std::vector<std::shared_ptr<std::string const>> m_queue; std::vector<std::shared_ptr<std::string>> m_queue;
}; };
#endif // __WEBSOCKETSIGNALSESSION_H__ #endif // __WEBSOCKETSIGNALSESSION_H__

View File

@ -398,6 +398,7 @@ http {
server { server {
listen 443 ssl; listen 443 ssl;
server_name amass.fun; server_name amass.fun;
proxy_http_version 1.1;
ssl_certificate cert/amass.fun.pem; ssl_certificate cert/amass.fun.pem;
ssl_certificate_key cert/amass.fun.key; ssl_certificate_key cert/amass.fun.key;
include server.conf; include server.conf;
@ -406,6 +407,7 @@ http {
server { server {
listen 443 ssl; listen 443 ssl;
server_name mirror.amass.fun; server_name mirror.amass.fun;
proxy_http_version 1.1;
ssl_certificate cert/mirror.amass.fun.pem; ssl_certificate cert/mirror.amass.fun.pem;
ssl_certificate_key cert/mirror.amass.fun.key; ssl_certificate_key cert/mirror.amass.fun.key;
include server.conf; include server.conf;

View File

@ -29,7 +29,6 @@ location ^~ /api/v1/search/ {
} }
location ^~ /api/v1/auth { location ^~ /api/v1/auth {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade"; proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
@ -53,7 +52,6 @@ location /wt {
} }
location = /wt/app.js { location = /wt/app.js {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade"; proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
@ -78,7 +76,6 @@ location /freedom {
} }
proxy_redirect off; proxy_redirect off;
proxy_pass http://127.0.0.1:8089; proxy_pass http://127.0.0.1:8089;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade"; proxy_set_header Connection "upgrade";
proxy_set_header Host $host; proxy_set_header Host $host;

View File

@ -116,6 +116,8 @@ std::string Client::randomId(size_t length) {
Client::Client() : m_d{new ClientPrivate(this)} { Client::Client() : m_d{new ClientPrivate(this)} {
rtc::InitLogger(rtc::LogLevel::Info); rtc::InitLogger(rtc::LogLevel::Info);
m_d->config.iceServers.emplace_back("stun:amass.fun:5439");
m_d->config.iceServers.emplace_back(rtc::IceServer("amass.fun", 5439, "amass", "88888888"));
m_id = randomId(4); m_id = randomId(4);
LOG(info) << "The local ID is " << m_id; LOG(info) << "The local ID is " << m_id;
log(std::format("The local ID is {}", m_id)); log(std::format("The local ID is {}", m_id));

View File

@ -1,7 +1,19 @@
WT_DECLARE_WT_MEMBER(1, JavaScriptConstructor, "WebRTCClient", function (WT, client, offerId, offerBtn, sendMsg, sendBtn, textBrowser, localId, url) { WT_DECLARE_WT_MEMBER(1, JavaScriptConstructor, "WebRTCClient", function (WT, client, offerId, offerBtn, sendMsg, sendBtn, textBrowser, localId, url) {
this.peerConnectionMap = {}; this.peerConnectionMap = {};
this.dataChannelMap = {}; this.dataChannelMap = {};
this.config = {}; this.ws = null;
this.config = {
iceServers: [
{
urls: "stun:amass.fun:5439"
},
{
urls: "turns:amass.fun",
username: 'amass',
credential: '88888888'
},
],
};
this.log = (text) => { this.log = (text) => {
textBrowser.value = `${textBrowser.value}\n${text}`; textBrowser.value = `${textBrowser.value}\n${text}`;
}; };
@ -89,12 +101,26 @@ WT_DECLARE_WT_MEMBER(1, JavaScriptConstructor, "WebRTCClient", function (WT, cli
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const ws = new WebSocket(url); const ws = new WebSocket(url);
ws.onopen = () => resolve(ws); ws.onopen = () => resolve(ws);
ws.onerror = () => reject(new Error('WebSocket error')); ws.onerror = () => {
ws.onclose = () => console.error('WebSocket disconnected'); if (this.pingTimer) {
clearInterval(this.pingTimer);
this.pingTimer = 0;
}
reject(new Error('WebSocket error'));
};
ws.onclose = () => {
if (this.pingTimer) {
clearInterval(this.pingTimer);
this.pingTimer = 0;
}
console.error('WebSocket disconnected');
};
ws.onmessage = (e) => { ws.onmessage = (e) => {
if (typeof (e.data) != 'string') return; if (typeof (e.data) != 'string') return;
const message = JSON.parse(e.data); const message = JSON.parse(e.data);
console.log(message); if (message.type == undefined || message.type != "pong") {
console.log(message);
}
const { id, type } = message; const { id, type } = message;
let pc = this.peerConnectionMap[id]; let pc = this.peerConnectionMap[id];
if (!pc) { if (!pc) {
@ -115,7 +141,6 @@ WT_DECLARE_WT_MEMBER(1, JavaScriptConstructor, "WebRTCClient", function (WT, cli
} }
}); });
break; break;
case 'candidate': case 'candidate':
pc.addIceCandidate({ pc.addIceCandidate({
candidate: message.candidate, candidate: message.candidate,
@ -134,6 +159,17 @@ WT_DECLARE_WT_MEMBER(1, JavaScriptConstructor, "WebRTCClient", function (WT, cli
offerBtn.disabled = false; offerBtn.disabled = false;
offerBtn.onclick = () => { offerBtn.onclick = () => {
this.offerPeerConnection(ws, offerId.value); this.offerPeerConnection(ws, offerId.value);
} };
this.ws = ws;
this.pingTimer = setInterval(() => {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({
type: "ping",
}));
} else {
clearInterval(this.pingTimer);
this.pingTimer = 0;
}
}, 3000);
}); });
}); });