297 lines
12 KiB
C#
297 lines
12 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.IO;
|
|
//using BCG.Utilities;
|
|
//using BCG.Utilities.General;
|
|
using System.Threading;
|
|
using mbts;
|
|
using bts;
|
|
using System.Linq;
|
|
using System.Reflection.Metadata.Ecma335;
|
|
|
|
namespace BCG {
|
|
/// <summary>
|
|
/// Keeps an ITCPConnection for talking to the server. It also monitors heartbeats
|
|
/// from the server, and in case of missing hbs, informs its clients, and tries to
|
|
/// restablish the connection.
|
|
/// Threads :
|
|
/// its assumed that IPubSubServerConnection functions (including doWork) will
|
|
/// be called from the same thread. ITCPMessageHandler.onData and
|
|
/// ITCPConnectionHandler.onConnection will be called on any arbitrary thread
|
|
///
|
|
/// </summary>
|
|
public class PubSubServerManagedTCPConnection : IPubSubServerConnection,// external facing interface to communicate msgs to Pubsubserver
|
|
ITCPMessageHandler, // to get messages from ITCPCOnnection
|
|
ITCPConnectionHandler { // to get connections from AsyncTCPConnector_APM
|
|
private ITCPConnection _connection, _new_connection;
|
|
private readonly BlutoSubAddress _server_address;
|
|
// if a message(with confirm) can not be sent , its id is queued here,
|
|
// on reconnection, _on_send_onfirm_callback is fired with a negative on these ids, so the user
|
|
//can re-send it. The re-send mechanism is not in implemented in this class, but by the user of this class
|
|
private ThreadSafeQueue<string> _negative_unsent_confs = new ThreadSafeQueue<string>();
|
|
// in onData, data is queued here, for polling
|
|
private SyncQueue<byte[]> _in_data_queue = new SyncQueue<byte[]>();
|
|
private DateTime _last_hb = DateTime.Now;
|
|
private PubSubServerConnectionStatusChange _conn_callback;
|
|
private PubSubServerDataDelegate _data_callback;
|
|
private SendConfirmationDelegate _on_send_confirm_callback;
|
|
private readonly TimeSpan _connection_drop_threshold =
|
|
new TimeSpan(0, 0, 0, 0,
|
|
PubSub3Config.instance.PS3_HeartBeatInterval * PubSub3Config.instance.PS3_MissingHeartBeatsForGC);
|
|
|
|
public PubSubServerManagedTCPConnection(string server_url)
|
|
: this(new BlutoSubAddress(server_url)) { }
|
|
|
|
public PubSubServerManagedTCPConnection(BlutoSubAddress server_address) {
|
|
_server_address = server_address;
|
|
_connect_to_ps_server();
|
|
}
|
|
|
|
private void _connect_to_ps_server() {
|
|
bts.Log.Gen.info($"PubSubServerManagedTCPConnection._connect_to_ps_server server: {_server_address}");
|
|
AsyncTCPConnector_APM.connect_to(_server_address, this);
|
|
}
|
|
|
|
#region IPubSubServerConnection Members
|
|
|
|
public void send_with_confirmation(byte[] data, ref string conf_id) {
|
|
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.sendWithConfirmation server: {_server_address} data: {data.Length} _connection : {_connection != null}");
|
|
if (_connection != null) {
|
|
_connection.sendWithConfirmation(data, ref conf_id, (msg_id, confirmed) => {
|
|
if (_on_send_confirm_callback != null)
|
|
_on_send_confirm_callback(msg_id, confirmed);
|
|
});
|
|
} else {
|
|
bts.Log.Gen.warn($"PubSubServerManagedTCPConnection.sendWithConfirmation server: {_server_address} no connection, buffering send");
|
|
conf_id = Guid.NewGuid().ToString();
|
|
_negative_unsent_confs.enqueue(conf_id);
|
|
}
|
|
}
|
|
|
|
private void _send(byte[] data) {
|
|
bts.Log.Gen.info($"PubSubServerManagedTCPConnection._send server: {_server_address} data: {data.Length} _connection : {_connection != null}");
|
|
if (_connection != null) {
|
|
bts.Log.Gen.info("PubSubServerManagedTCPConnection.send server: " + _server_address + "data: " + data.Length);
|
|
_connection.send(data);
|
|
}
|
|
}
|
|
|
|
public void send(bts.PubSubClientMessage ps_msg) {
|
|
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_address} ps_msg: {ps_msg}");
|
|
var msg_bytes = ps_msg.serialize_into_bytes();
|
|
PubSubClientMessage msg_retrv = new PubSubClientMessage();
|
|
msg_retrv.consruct_deserialize(msg_bytes);
|
|
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_address} msg_retrv: {msg_retrv}");
|
|
_send(msg_bytes);
|
|
}
|
|
|
|
// private void send(Stream str) {
|
|
// BinaryReader br = new BinaryReader(str);
|
|
// _send(br.ReadBytes(Convert.ToInt32(str.Length - str.Position)));
|
|
// }
|
|
|
|
// private void send(PubSubMessage msg) {
|
|
// send(msg.to_stream());
|
|
// }
|
|
|
|
// public void send_with_confirmation(PubSubMessage msg, ref string conf_id) {
|
|
// var bytes = msg.to_bytes();
|
|
// send_with_confirmation(bytes, ref conf_id);
|
|
// }
|
|
|
|
public void send_with_confirmation(bts.PubSubClientMessage msg, ref string conf_id, SendConfirmationDelegate del) {
|
|
if (_connection == null) {
|
|
// quq
|
|
}
|
|
MemoryStream str = new MemoryStream();
|
|
msg.serialize_into_str(str);
|
|
var bytes = StreamUtilityMethods.getBytesFromStream(str);
|
|
_connection.sendWithConfirmation(bytes, ref conf_id, del);
|
|
}
|
|
|
|
public IEnumerable<bts.PubSubServerMessage> get_updates(TimeSpan timeout, int maxElements) {
|
|
List<byte[]> rv_raw = _in_data_queue.dequeueMultipleElements(Convert.ToInt32(timeout.TotalMilliseconds), maxElements);
|
|
List<bts.PubSubServerMessage> rv = new List<PubSubServerMessage>();
|
|
var i = 0;
|
|
foreach (var b in rv_raw) {
|
|
PubSubServerMessage ps_msg = new PubSubServerMessage();
|
|
ps_msg.consruct_deserialize(b);
|
|
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.get_updates downloaded: {ps_msg} msg_no: {i} / {rv_raw.Count}");
|
|
rv.Add(ps_msg);
|
|
i++;
|
|
}
|
|
return rv;
|
|
}
|
|
|
|
public string server_url {
|
|
get { return _server_address.ToString(); }
|
|
}
|
|
|
|
public string client_url {
|
|
get {
|
|
string rv = "";
|
|
lock (this) {
|
|
if (_connection == null) {
|
|
rv = "";
|
|
} else {
|
|
if (PubSub3Config.instance.PS3_IPTranslation == null || PubSub3Config.instance.PS3_IPTranslation == String.Empty) {
|
|
string ip;
|
|
int port;
|
|
_connection.getSelfAddress(out ip, out port);
|
|
rv = new BlutoSubAddress(ip, port).ToString();
|
|
} else {
|
|
rv = "";
|
|
}
|
|
}
|
|
}
|
|
return rv;
|
|
}
|
|
}
|
|
|
|
public void register_connection_callback(PubSubServerConnectionStatusChange del) {
|
|
_conn_callback = del;
|
|
}
|
|
|
|
public void register_data_callback(PubSubServerDataDelegate del) {
|
|
_data_callback = del;
|
|
}
|
|
|
|
public void register_send_confirmation_callback(SendConfirmationDelegate del) {
|
|
_on_send_confirm_callback = del;
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region IDisposable Members
|
|
|
|
private bool _is_disposed = false;
|
|
public void Dispose() {
|
|
bts.Log.Gen.info("PubSubServerManagedTCPConnection.Dispose");
|
|
//throw new Exception("The method or operation is not implemented.");
|
|
if (_connection != null) {
|
|
_connection.Dispose();
|
|
|
|
}
|
|
_is_disposed = true;
|
|
}
|
|
public bool isDisposed {
|
|
get {
|
|
return _is_disposed;
|
|
}
|
|
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region ITCPMessageHandler Members
|
|
|
|
/// <summary>
|
|
/// This method is executed on an arbitrary CLR thread. To avoid blocking it
|
|
/// data is written to the queue and method returns. myLastHB being a primitive
|
|
/// (long) is safe for multi threaded operations
|
|
/// </summary>
|
|
/// <param name="message"></param>
|
|
public void onData(RemoteMessage message) {
|
|
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onData message: {message}");
|
|
// TODO check for disconenction
|
|
switch (message.messageType) {
|
|
case RemoteMessageType.Data:
|
|
if (_data_callback != null)
|
|
_data_callback(message.remoteConnectionInfo.ToString(), message.message);
|
|
else
|
|
_in_data_queue.enqueue(message.message);
|
|
break;
|
|
case RemoteMessageType.Heartbeat:
|
|
_last_hb = DateTime.Now;
|
|
break;
|
|
case RemoteMessageType.Connection:
|
|
_conn_callback(_server_address.ToString(), true);
|
|
break;
|
|
case RemoteMessageType.Disconnection:
|
|
if (_conn_callback != null)
|
|
_conn_callback(_server_address.ToString(), false);
|
|
_connection.Dispose();
|
|
_connect_to_ps_server();
|
|
break;
|
|
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region ITCPConnectionHandler Members
|
|
|
|
/// will be called on on an rbitrary .Net thread
|
|
public void onConnection(ITCPConnection connection) {
|
|
string ip;
|
|
int port;
|
|
connection.getPeerAddress(out ip, out port);
|
|
BlutoSubAddress add = new BlutoSubAddress(ip, port);
|
|
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onConnection add: {add.ToString()} connection type: {connection.GetType()}");
|
|
if (add.ToString() == _server_address.ToString()) {
|
|
_last_hb = DateTime.Now;
|
|
_new_connection = connection;
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
void _dispose_and_reconnect_if_missing_hb() {
|
|
if (!_connection.isDisposed) {
|
|
TimeSpan hb_interval = DateTime.Now - _last_hb;
|
|
bool hb_missed = hb_interval > _connection_drop_threshold;
|
|
if (hb_missed) {
|
|
if (_conn_callback != null)
|
|
_conn_callback(_server_address.ToString(), false);
|
|
bts.Log.Gen.info("PubSubServerManagedTCPConnection._dispose_and_reconnect_if_missing_hb disposing connecion: {myServerAddress}");
|
|
_connection.Dispose();
|
|
_connect_to_ps_server();
|
|
}
|
|
} else {
|
|
// already disposed, nothing to do
|
|
}
|
|
}
|
|
|
|
void _check_for_new_connection() {
|
|
if (_new_connection != null) {
|
|
_connection = _new_connection;
|
|
_new_connection = null; // since we are using its presence as a marker of nw connections
|
|
bts.Log.Gen.info("PubSubServerManagedTCPConnection._check_for_new_connection assigning new connection");
|
|
_connection.register(this);
|
|
if (_conn_callback != null)
|
|
_conn_callback(_server_address.ToString(), true);
|
|
if (_on_send_confirm_callback != null) {
|
|
var msg_ids = _negative_unsent_confs.dequeueAll();
|
|
foreach (var id in msg_ids)
|
|
_on_send_confirm_callback(id, false);
|
|
}
|
|
}
|
|
}
|
|
|
|
#region IWorker Members
|
|
|
|
/// <summary>
|
|
/// should be called on the same thread as the other user functions.
|
|
/// the design only allows for onConnection to be on a different
|
|
/// thread.
|
|
/// </summary>
|
|
public void doWork() {
|
|
//_dispose_and_reconnect_if_missing_hb();
|
|
//try {
|
|
_check_for_new_connection();
|
|
// } catch (Exception ex) {
|
|
// bts.Log.Gen.warn($"PubsSubServerManagedTCPConnection.doWork ex: {ex}");
|
|
// }
|
|
}
|
|
|
|
#endregion
|
|
|
|
// private void myOnSendConfirm(string messageId, bool confirmed) {
|
|
// _negative_confs.enqueue(new Pair<string, bool>(messageId, confirmed));
|
|
// }
|
|
|
|
}
|
|
} |