69 lines
2.3 KiB
C#
69 lines
2.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using bts;
|
|
using System.Threading;
|
|
|
|
namespace BCG {
|
|
|
|
public class SimpleTCPServer : ITCPConnectionHandler, ITCPMessageHandler {
|
|
int _n_msgs_received = 0;
|
|
bool _isDisposed = false;
|
|
AsyncTCPConnectionAcceptor_AsyncWrapper _acceptor;
|
|
IDictionary<RemoteConnectionInfo, ITCPConnection> _conn_map = new Dictionary<RemoteConnectionInfo, ITCPConnection>();
|
|
readonly bool _echo_msg_back;
|
|
|
|
public SimpleTCPServer(int port, bool echo_msg_back) {
|
|
Log.Gen.info($"SimpleTCPServer.const port: {port} echo_msg_back: {echo_msg_back}");
|
|
_acceptor = new AsyncTCPConnectionAcceptor_AsyncWrapper(port, this);
|
|
_echo_msg_back = echo_msg_back;
|
|
}
|
|
|
|
public void init() {
|
|
_acceptor.start();
|
|
}
|
|
|
|
|
|
public void onConnection(ITCPConnection connection) {
|
|
RemoteConnectionInfo rci = connection.get_peer_address();
|
|
_conn_map[rci] = connection;
|
|
bts.Log.Gen.info($"SimpleTCPServer.onConnection new client connected conn: {rci}");
|
|
connection.register(this);
|
|
}
|
|
|
|
|
|
public void onData(RemoteMessage msg) {
|
|
_n_msgs_received++;
|
|
var log_msg = $"SimpleTCPServer.onData msgs_received: {_n_msgs_received} msg: {msg} _echo_msg_back: {_echo_msg_back}";
|
|
Log.Gen.info(log_msg);
|
|
Console.WriteLine(log_msg);
|
|
if (!_echo_msg_back) {
|
|
return;
|
|
}
|
|
RemoteConnectionInfo rci = msg.remoteConnectionInfo;
|
|
ITCPConnection this_conn;
|
|
bool found = _conn_map.TryGetValue(rci, out this_conn);
|
|
if (!found) {
|
|
Log.Gen.error($"Could not find connection: {rci}");
|
|
return;
|
|
}
|
|
Log.Gen.info($"\n\n\nSimpleTCPServerAsync.onData msgs_received: {_n_msgs_received} msg: {msg} ci: {rci} NOW echoing it back\n\n\n");
|
|
if (msg.messageType == RemoteMessageType.Data) {
|
|
this_conn.send(msg.message);
|
|
} else {
|
|
if (msg.messageType == RemoteMessageType.Disconnection) {
|
|
var ci = msg.remoteConnectionInfo;
|
|
_conn_map.Remove(ci);
|
|
}
|
|
}
|
|
}
|
|
|
|
public bool isDisposed => _isDisposed;
|
|
|
|
public void Dispose() {
|
|
_conn_map.Values.DisposeAll();
|
|
Volatile.Write(ref _isDisposed, true);
|
|
_conn_map.Clear();
|
|
}
|
|
}
|
|
}
|