From 1ceea4af5a716876ead531ec885f7c3cb7b060e2 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Wed, 20 Dec 2023 11:32:53 -0500 Subject: [PATCH] Changing TCPUtils to use SocketAsyncEventArgs instead of TAP functions, simple client<->server works with echoing messages --- .../DataStreamPublisher/Program.cs | 44 +++-- .../PubSub/ManagedTCP/AsyncTCPConnection2.cs | 136 +++++---------- .../PubSub/ManagedTCP/TCPSocketUtils.cs | 155 +++++++++++++----- .../PubSub/Testing/SimpleTCPClient.cs | 95 ++--------- .../PubSub/Testing/SimpleTCPServer.cs | 83 ++-------- .../PubSub/Testing/SocketEventArgExample.cs | 0 src/DataStreamSuite/PubSubServer/Program.cs | 9 +- 7 files changed, 217 insertions(+), 305 deletions(-) create mode 100644 src/DataStreamSuite/PubSub/Testing/SocketEventArgExample.cs diff --git a/src/DataStreamSuite/DataStreamPublisher/Program.cs b/src/DataStreamSuite/DataStreamPublisher/Program.cs index 16a58ff6e..4d8fcbb3f 100644 --- a/src/DataStreamSuite/DataStreamPublisher/Program.cs +++ b/src/DataStreamSuite/DataStreamPublisher/Program.cs @@ -6,16 +6,14 @@ using Bts.DataStreamExpressions; using System.Collections.Generic; using BCG; +using System.Threading; bts.Log.Gen.info($"Starting DSPublisher"); Console.WriteLine("Starting DSPublisher..."); -static void init(string[] args) -{ - Console.WriteLine("Hit key to continue"); - Console.ReadLine(); - Func login = async (l, p) => - { +bool run_echo_tcp_client_only = true; +static void init(string[] args) { + Func login = async (l, p) => { var login = l; var passwd = p; var service_ctx = bts.api.core.ServiceContext.create(); @@ -25,29 +23,32 @@ static void init(string[] args) Configuration.initialize(); Task.Run(async () => await login("bts", String.Empty)); } - init(args); -_publish_streams(); +if (run_echo_tcp_client_only) + await start_echo_client(); +else + _publish_streams(); -static ViewStream build_stream(string stream_expression) -{ - try - { +static ViewStream build_stream(string stream_expression) { + try { var exp = DataStreamExpressionsInterpreter.Evaluate(stream_expression); var rv = exp.getView(new Dictionary(0)); return rv; - } - catch (Exception ex) - { + } catch (Exception ex) { bts.Log.assert(false, $"Could not build stream: {stream_expression} ex: {ex}"); return null; } } +async Task start_echo_client() { + Console.WriteLine("Starting DSPublisher in TCP client echo mode, Hit key to continue"); + Console.ReadLine(); + await SimpleTCPClientAsync.start("127.0.0.1", 12345); + Task.Delay(1000000000).Wait(); +} -void _publish_streams() -{ +void _publish_streams() { PubTableBroker pb_broker = new PubTableBroker(); CloudStreamManager csm = new CloudStreamManager(); // get it from config @@ -60,16 +61,14 @@ void _publish_streams() {"literal_420","literal(\"x\", \"420.0\")"}, // {"bbo_ts","timeSeries(bbo())"} }; - foreach (var kv in streams_to_publish) - { + foreach (var kv in streams_to_publish) { var name = kv.Key; var exp = kv.Value; BCG.ViewStream vs = build_stream(exp); ViewPublisher vpub = new ViewPublisher(name, pb_broker, vs); vs.onChange += on_change; } - while (true) - { + while (true) { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); ViewStreamDatabase.instance.doWork(); csm.doWork(); @@ -78,7 +77,6 @@ void _publish_streams() -void on_change(object obj) -{ +void on_change(object obj) { bts.Log.Gen.info($"DSPublisher on_change dp: {obj}"); } \ No newline at end of file diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection2.cs b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection2.cs index 3048fa1a5..524b44f58 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection2.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/AsyncTCPConnection2.cs @@ -16,12 +16,10 @@ using System.Reflection; using BCG.Utilities.General; using System.Net.WebSockets; -namespace BCG -{ +namespace BCG { - public class AsyncTCPConnection2 : ITCPConnection, IWorker, IDisposable - { - //private Socket _socket; + public class AsyncTCPConnection2 : ITCPConnection, IWorker, IDisposable { + private Socket _socket; // tied to the socket above private NetworkStream _nw_stream; private readonly ConnectionSide _side; @@ -37,14 +35,12 @@ namespace BCG private bool _is_disposed = false; SyncQueue _data_send_queue = new SyncQueue(); - public class QueuedMessage - { + public class QueuedMessage { public string id; public SendConfirmationDelegate del; public byte[] data; - public QueuedMessage(string id, SendConfirmationDelegate del, byte[] data) - { + public QueuedMessage(string id, SendConfirmationDelegate del, byte[] data) { id = id; del = del; data = data; @@ -55,15 +51,13 @@ namespace BCG } - public enum ConnectionSide - { + public enum ConnectionSide { Client, Server } - public AsyncTCPConnection2(Socket socket, ConnectionSide side) - { - //_socket = socket; + public AsyncTCPConnection2(Socket socket, ConnectionSide side) { + _socket = socket; _nw_stream = new NetworkStream(socket); _side = side; IPEndPoint r_ep = socket.RemoteEndPoint as IPEndPoint; @@ -73,8 +67,7 @@ namespace BCG _self_address = new RemoteConnectionInfo(loc_ep.Address.ToString(), loc_ep.Port); } - public void register(ITCPMessageHandler message_handler) - { + public void register(ITCPMessageHandler message_handler) { _message_handler = message_handler; Task.Run(async () => _keep_reading()); Task.Run(async () => await _keep_sending()); @@ -84,26 +77,19 @@ namespace BCG } // this thread pulls - private async Task _keep_sending() - { + private async Task _keep_sending() { bts.Log.Gen.info($"TCPConnection._keep_sending starting"); - while (!_is_disposed) - { - try - { + while (!_is_disposed) { + try { QueuedMessage m = _data_send_queue.dequeue(100); - if (m == null) - { + if (m == null) { continue; } await send_async(m.data); - if (String.IsNullOrEmpty(m.id)) - { + if (String.IsNullOrEmpty(m.id)) { m.del(m.id, true); } - } - catch (Exception ex) - { + } catch (Exception ex) { bts.Log.Gen.error($"TCPConnection._keep_sending ex: {ex.Message}"); await Task.Delay(100); _handle_error(ex); @@ -111,19 +97,14 @@ namespace BCG } } - private async Task _keep_reading() - { + private async Task _keep_reading() { bts.Log.Gen.info($"TCPConnection._keep_reading starting"); - while (!_is_disposed) - { - try - { + while (!_is_disposed) { + try { byte[] msg = await TCPSocketUtils.read_bytes_async(_nw_stream); bts.Log.Gen.info($"AsyncTCPConnection2._keep_reading side: {_side} self: {get_self_address()} peer: {get_peer_address()} msg len: {msg.Length}"); await _handle_msg(msg); - } - catch (Exception ex) - { + } catch (Exception ex) { bts.Log.Gen.error($"TCPConnection._keep_reading ex: {ex.Message}"); await Task.Delay(100); _handle_error(ex); @@ -131,27 +112,22 @@ namespace BCG } } - private async Task _handle_msg(byte[] msg) - { + private async Task _handle_msg(byte[] msg) { // read the first byte to read the msg type and deal with it accordingly BinaryReader br = new BinaryReader(new MemoryStream(msg)); byte msg_type = br.ReadByte(); - if (msg_type == _msg_type_data) - { + if (msg_type == _msg_type_data) { byte[] data = br.ReadBytes(msg.Length - 1); RemoteMessage m = new RemoteMessage(data, RemoteMessageType.Data, _peer_address); _message_handler.onData(m); - } - else - { + } else { RemoteMessage m = new RemoteMessage(null, RemoteMessageType.Heartbeat, _peer_address); _message_handler.onData(m); } } // not very efficient - private static byte[] _prefix_msg_type(byte[] data) - { + private static byte[] _prefix_msg_type(byte[] data) { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(_msg_type_data); @@ -160,17 +136,13 @@ namespace BCG return ms.ToArray(); } - private async void _handle_error(Exception ex) - { + private async void _handle_error(Exception ex) { bts.Log.Gen.error($"TCPConnection._handle_error ex: {ex}"); - try - { + try { var socket = _nw_stream.Socket; socket.Close(); socket.Dispose(); - } - catch (Exception ex2) - { + } catch (Exception ex2) { bts.Log.Gen.error($"TCPConnection._handle_error got exception when closing Socket ex: {ex}"); } _is_disposed = true; @@ -180,54 +152,43 @@ namespace BCG public void send_with_confirmation(byte[] data, string confId, SendConfirmationDelegate del) { } - public async Task send_with_confirmation_async(byte[] data, string conf_id, SendConfirmationDelegate del) - { - try - { + public async Task send_with_confirmation_async(byte[] data, string conf_id, SendConfirmationDelegate del) { + try { conf_id = (++_msg_id).ToString(); await TCPSocketUtils.send_bytes_async(_nw_stream, data); del(conf_id, true); - } - catch (Exception ex) - { + } catch (Exception ex) { _handle_error(ex); } } - public void sendWithConfirmation(byte[] data, ref string conf_id, SendConfirmationDelegate del) - { + public void sendWithConfirmation(byte[] data, ref string conf_id, SendConfirmationDelegate del) { conf_id = (++_msg_id).ToString(); send(data); del(conf_id, true); } - public void send(byte[] data) - { + public void send(byte[] data) { Task.Run(async () => await send_async(data)); bts.Log.Gen.info($"AsyncTCPConnection2.send self: {get_self_address()} peer: {get_peer_address()} msg len: {data.Length} sent successfully"); //_data_send_queue.enqueue(new QueuedMessage(data)); } - public async Task send_async(byte[] data) - { + public async Task send_async(byte[] data) { // prefix 4 bytes for type (data vs hb) MemoryStream str = new MemoryStream(); BinaryWriter bw = new BinaryWriter(str); bw.Write(_msg_type_data); bw.Write(data); - try - { + try { await TCPSocketUtils.send_bytes_async(_nw_stream, str.ToArray()); - } - catch (Exception ex) - { + } catch (Exception ex) { bts.Log.Gen.error($"AsyncTCPConnection2.send_async ex: {ex}"); _handle_error(ex); } } - public void getPeerAddress(out string ip, out int port) - { + public void getPeerAddress(out string ip, out int port) { ip = _peer_address.ip; port = _peer_address.port; ///.Net has some problems getting the port, so using @@ -238,31 +199,26 @@ namespace BCG //port = addr.sin_port; } - public RemoteConnectionInfo get_peer_address() - { + public RemoteConnectionInfo get_peer_address() { string ip; int port; getPeerAddress(out ip, out port); return new RemoteConnectionInfo(ip, port); } - public RemoteConnectionInfo get_self_address() - { + public RemoteConnectionInfo get_self_address() { string ip; int port; getSelfAddress(out ip, out port); return new RemoteConnectionInfo(ip, port); } - public void getSelfAddress(out string ip, out int port) - { + public void getSelfAddress(out string ip, out int port) { ip = _self_address.ip; port = _self_address.port; } - private async void _send_hb() - { - if (_last_hb_sent - DateTime.Now > _hb_period) - { + private async void _send_hb() { + if (_last_hb_sent - DateTime.Now > _hb_period) { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(_msg_type_hb); @@ -272,22 +228,18 @@ namespace BCG } } - public void doWork() - { + public void doWork() { _send_hb(); } - public void Dispose() - { + public void Dispose() { _nw_stream.Close(); _nw_stream.Dispose(); _is_disposed = true; } - public bool isDisposed - { - get - { + public bool isDisposed { + get { return _is_disposed; } } diff --git a/src/DataStreamSuite/PubSub/ManagedTCP/TCPSocketUtils.cs b/src/DataStreamSuite/PubSub/ManagedTCP/TCPSocketUtils.cs index ed0943d40..b86a89e2b 100644 --- a/src/DataStreamSuite/PubSub/ManagedTCP/TCPSocketUtils.cs +++ b/src/DataStreamSuite/PubSub/ManagedTCP/TCPSocketUtils.cs @@ -11,38 +11,33 @@ using System.Xml.Serialization; using System.Reflection; using BCG.Utilities.General; using System.Net.WebSockets; +using bts; +using System.Threading; -namespace BCG -{ +namespace BCG { // utility functions for TCP socket async communications. Does the following // client to server connect // server to client connect accepting // send data // receive data - public static class TCPSocketUtils - { + public static class TCPSocketUtils { #region socket opening and connecting // keeps accepting connections forever public static async Task accept_connections_async(string ip, int port, ITCPConnectionHandler handler, - TimeSpan wait_after_error) - { + TimeSpan wait_after_error) { IPAddress ipAddress = String.IsNullOrEmpty(ip) ? IPAddress.Parse(ip) : IPAddress.Any; var ip_end_point = new IPEndPoint(ipAddress, port); Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.Bind(ip_end_point); listener.Listen(10); Socket client_socket = null; - while (true) - { - try - { + while (true) { + try { // keeps on accepting connections client_socket = await listener.AcceptAsync(); AsyncTCPConnection2 new_conn = new(client_socket, AsyncTCPConnection2.ConnectionSide.Server); handler.onConnection(new_conn); - } - catch (Exception ex) - { + } catch (Exception ex) { bts.Log.Gen.error($"TCPConnection.accept ex: {ex} trying again"); Task.Delay(wait_after_error); } @@ -52,13 +47,10 @@ namespace BCG // connects to the server and ona successful connection, calls con__handler.on_connection_async with an ITCPConnection. // In case of failures to connect it waits for a given amount of time before retrying public static async Task connect_to_server_async(string ip, int server_port, ITCPConnectionHandler conn_handler, - TimeSpan wait_after_failed_attempt, int n_max_attempts = 1024) - { + TimeSpan wait_after_failed_attempt, int n_max_attempts = 1024) { Socket client_socket = null; - for (int i = 0; i < n_max_attempts; i++) - { - try - { + for (int i = 0; i < n_max_attempts; i++) { + try { string log_conn = $"{ip}:{server_port}"; bts.Log.Gen.info($"AsyncTCPConnection2.connect_to_server conn: {log_conn} attempt no: {i}"); IPAddress server_ip_address = IPAddress.Parse(ip); @@ -68,9 +60,7 @@ namespace BCG ITCPConnection new_conn = new AsyncTCPConnection2(client_socket, AsyncTCPConnection2.ConnectionSide.Client); conn_handler.onConnection(new_conn); break; - } - catch (Exception ex) - { + } catch (Exception ex) { bts.Log.Gen.error($"AsyncTCPConnection2.connect_to_server threw ex: {ex}, will reattempt now"); Task.Delay(wait_after_failed_attempt); } @@ -83,31 +73,114 @@ namespace BCG // prefixes the size of the data and sends it as 2 sends, for size and data // (can be done as one send perhaps) - public static async Task send_bytes_async(NetworkStream nw_stream, byte[] data_buff) - { - var data_sz = data_buff.Length; + public static async Task send_bytes_async(NetworkStream nw_stream, byte[] data_buff) { + Log.Gen.info($"send_bytes_async data_buff: {data_buff.Length}"); + // var data_sz = data_buff.Length; byte[] sz_buff = new byte[4]; - // aend the size first + // // send the size first BinaryWriter bw = new BinaryWriter(new MemoryStream(sz_buff)); - bw.Write(data_sz); - await nw_stream.WriteAsync(sz_buff, 0, 4); - await nw_stream.WriteAsync(data_buff, 0, data_buff.Length); + bw.Write(data_buff.Length); + await SendMessageAsync(nw_stream.Socket, new Memory(sz_buff)); + // await nw_stream.WriteAsync(sz_buff, 0, 4); + // await nw_stream.WriteAsync(data_buff, 0, data_buff.Length); + Memory mem = new Memory(data_buff); + await SendMessageAsync(nw_stream.Socket, mem); } + public static async Task SendMessageAsync(Socket sock, Memory mem_buff) { + // use ManualResetEvent to make it non async + Log.Gen.info($"SendMessageAsync mem: {mem_buff.Length}"); + SocketAsyncEventArgs evargs = new SocketAsyncEventArgs(); + evargs.SetBuffer(mem_buff); + var tcs = new TaskCompletionSource(); + evargs.Completed += (s, e) => { + Log.Gen.info($"SendMessageAsync completed asynchronously e: {sock_event_args_txt(e)}"); + tcs.SetResult(true); + }; + bool completed = !sock.SendAsync(evargs); + if (completed) { + Log.Gen.info($"SendMessageAsync completed synchronously e: {sock_event_args_txt(evargs)}"); + tcs.SetResult(true); + } + await tcs.Task; + + } // reads the bytes on a connected socket, by doing the opposite of the above, // reads the size first and then the data - public static async Task read_bytes_async(NetworkStream nw_stream) - { - byte[] sz_buffer = new byte[4]; - //Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. - int bytesRead = await nw_stream.ReadAsync(sz_buffer, 0, sz_buffer.Length); - BinaryReader br = new BinaryReader(new MemoryStream(sz_buffer)); - int msg_sz = br.ReadInt32(); - byte[] data_buffer = new byte[msg_sz]; - bytesRead = await nw_stream.ReadAsync(data_buffer, 0, data_buffer.Length); - //Console.WriteLine($"read_bytes sz: {data_buffer.Length}"); - return data_buffer; + public static async Task read_bytes_async(NetworkStream nw_stream) { + // byte[] data_buffer; + // try { + // byte[] sz_buffer = new byte[4]; + // //Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. + // int bytesRead = await nw_stream.ReadAsync(sz_buffer, 0, sz_buffer.Length); + // BinaryReader br = new BinaryReader(new MemoryStream(sz_buffer)); + // int msg_sz = br.ReadInt32(); + // data_buffer = new byte[msg_sz]; + // bytesRead = await nw_stream.ReadAsync(data_buffer, 0, data_buffer.Length); + // Log.Gen.info($"read_bytes_async intended: {msg_sz} received: {bytesRead}"); + // } catch (Exception ex) { + // Log.Gen.error($"read_bytes_async exception: {ex}"); + // return new byte[] { }; + // } + // //Console.WriteLine($"read_bytes sz: {data_buffer.Length}"); + // return data_buffer; + return ReceiveSizePrefixedMessageAsync(nw_stream.Socket); + } + + static string sock_event_args_txt(SocketAsyncEventArgs seargs) { + return $"err: {seargs.SocketError} bytes: {seargs.BytesTransferred}"; + } + + // this is a limited sync wrapper ovr the async ReceiveAsync + static byte[] ReceiveSizePrefixedMessageAsync(Socket socket) { + const int buffer_size = 4; // Size of the buffer to read the message size + + var size_buffer = new byte[buffer_size]; + var size_event_args = new SocketAsyncEventArgs(); + size_event_args.SetBuffer(size_buffer, 0, buffer_size); + var size_completed_event = new ManualResetEvent(false); + + size_event_args.Completed += (sender, e) => { + Log.Gen.info($"ReceiveSizePrefixedMessageAsync async completed (msg len) e: {sock_event_args_txt(e)}"); + size_completed_event.Set(); // Signal that the size receive operation is complete + }; + + if (!socket.ReceiveAsync(size_event_args)) { + Log.Gen.info($"ReceiveSizePrefixedMessageAsync msg size read completed synchronously e: {sock_event_args_txt(seargs: size_event_args)}"); + // If ReceiveAsync completed synchronously, set the event manually + size_completed_event.Set(); + } + + size_completed_event.WaitOne(); // Wait for the size receive operation to complete + + int message_size = BitConverter.ToInt32(size_buffer, 0); + Log.assert_d(message_size > 0, $"message_size: {message_size}"); + Log.Gen.info($"ReceiveSizePrefixedMessageAsync message_size: {message_size}"); + // at this ppint message sz has been read, now read the data + + var message_buffer = new byte[message_size]; + var message_event_args = new SocketAsyncEventArgs(); + message_event_args.SetBuffer(message_buffer, 0, message_size); + var message_completed_event = new ManualResetEvent(false); + + message_event_args.Completed += (sender, e) => { + Log.Gen.info($"ReceiveSizePrefixedMessageAsync async completed (msg) e: {sock_event_args_txt(e)}"); + message_completed_event.Set(); // Signal that the message receive operation is complete + }; + + if (!socket.ReceiveAsync(message_event_args)) { + Log.Gen.info($"ReceiveSizePrefixedMessageAsync msg read completed synchronously e: {sock_event_args_txt(seargs: message_event_args)}"); + // If ReceiveAsync completed synchronously, set the event manually + message_completed_event.Set(); + } + + message_completed_event.WaitOne(); // Wait for the message receive operation to complete + + return message_buffer; } - #endregion } + + + + #endregion } \ No newline at end of file diff --git a/src/DataStreamSuite/PubSub/Testing/SimpleTCPClient.cs b/src/DataStreamSuite/PubSub/Testing/SimpleTCPClient.cs index bfd444d01..775a40b70 100644 --- a/src/DataStreamSuite/PubSub/Testing/SimpleTCPClient.cs +++ b/src/DataStreamSuite/PubSub/Testing/SimpleTCPClient.cs @@ -10,52 +10,47 @@ using Spark.Core.Reactive; using System.Security.Cryptography.X509Certificates; using BCG; -namespace BCG -{ +namespace BCG { // This uses AsyncTCPConnection2's stateful async functions - public class SimpleTCPClientAsync : ITCPConnectionHandler, ITCPMessageHandler - { + public class SimpleTCPClientAsync : ITCPConnectionHandler, ITCPMessageHandler { AsyncTCPConnection2 _conn = null; int _m_msgs_received = 0; - public static async Task start(string ip, int port) - { + UInt32 msg_sz = 1024 * 1024 * 1024; + int wait_time_ms = 10000; + public static async Task start(string ip, int port) { SimpleTCPClientAsync c = new SimpleTCPClientAsync(ip, port); c.connect(); } - public void connect() - { + public void connect() { Task.Run(async () => await TCPSocketUtils.connect_to_server_async("127.0.0.1", 12345, this, TimeSpan.FromSeconds(2))); } - public void onConnection(ITCPConnection connection) - { - Console.WriteLine("SimpleTCPClientAsync.onConnection connected to server, starting task to send data in a loop"); + public void onConnection(ITCPConnection connection) { + string ip; int port; + connection.getPeerAddress(out ip, out port); + Console.WriteLine($"SimpleTCPClientAsync.onConnection connected to server ip: {ip} port: {port}, starting task to send data in a loop"); connection.register(this); // start sending data - Task.Run(async () => - { - byte[] buff = new byte[1024]; - for (int i = 0; i < buff.Length; i++) - { + Task.Run(async () => { + byte[] buff = new byte[msg_sz]; + for (int i = 0; i < buff.Length; i++) { buff[i] = (byte)i; } _conn = connection as AsyncTCPConnection2; - while (!_conn.isDisposed) - { + while (!_conn.isDisposed) { + Console.WriteLine($"SimpleTCPClientAsync sending data len: {buff.Length}"); await _conn.send_async(buff); - await Task.Delay(100); + await Task.Delay(wait_time_ms); } }); } - public void onData(RemoteMessage msg) - { + public void onData(RemoteMessage msg) { _m_msgs_received++; Console.WriteLine($"SimpleTCPClientAsync.onData n_msgs: {_m_msgs_received} msg: {msg}"); - if (msg.messageType == RemoteMessageType.Disconnection) - { + if (msg.messageType == RemoteMessageType.Disconnection) { connect(); } } @@ -67,58 +62,4 @@ namespace BCG public SimpleTCPClientAsync(string ip, int port) { } } - public class SimpleTCPClient : ITCPConnectionHandler, ITCPMessageHandler - { - private int _n_msgs_received = 0; - AsyncTCPConnection2 _conn = null; - - public static void start(string ip, int port) - { - SimpleTCPClient c = new SimpleTCPClient(ip, port); - c.connect(); - } - - public void connect() - { - Console.WriteLine("SimpleTCPClient.onConnection connect() called"); - ClientToServerManagedTCPConnector.connect_to(new BlutoSubAddress("bluto://127.0.0.1:12345"), this, TimeSpan.FromSeconds(1)); - } - - public void onConnection(ITCPConnection connection) - { - _conn = connection as AsyncTCPConnection2; - Console.WriteLine("SimpleTCPClient.onConnection connected to server, starting task to send data in a loop"); - _conn.register(this); - byte[] buff = new byte[1024]; - for (int i = 0; i < buff.Length; i++) - { - buff[i] = (byte)i; - } - - - while (!_conn.isDisposed) - { - _conn.send(buff); - System.Threading.Thread.Sleep(1000); - } - - } - - public void onData(RemoteMessage msg) - { - _n_msgs_received++; - Console.WriteLine($"SimpleTCPClient.onData messages received: {_n_msgs_received} msg: {msg} messages received: {_n_msgs_received}"); - if (msg.messageType == RemoteMessageType.Disconnection) - { - connect(); - } - } - - public bool isDisposed { get { return false; } } - - public void Dispose() { } - - public SimpleTCPClient(string ip, int port) { } - - } } diff --git a/src/DataStreamSuite/PubSub/Testing/SimpleTCPServer.cs b/src/DataStreamSuite/PubSub/Testing/SimpleTCPServer.cs index 4cb24c4fc..e806364cc 100644 --- a/src/DataStreamSuite/PubSub/Testing/SimpleTCPServer.cs +++ b/src/DataStreamSuite/PubSub/Testing/SimpleTCPServer.cs @@ -16,64 +16,46 @@ using System.Reflection; using System.Data; using System.Collections.Generic; -namespace BCG -{ +namespace BCG { - public class SimpleTCPServerAsync : ITCPConnectionHandler, ITCPMessageHandler - { + public class SimpleTCPServerAsync : ITCPConnectionHandler, ITCPMessageHandler { int _n_msgs_received = 0; SingleServerToClientManagedTCPConnectionAcceptor _acceptor = new SingleServerToClientManagedTCPConnectionAcceptor(); IDictionary _conn_map = new Dictionary(); - public static async Task start() - { + public static async Task start() { Console.WriteLine("SimpleTCPServer.start accepting socket connections"); - SimpleTCPServerAsync s = new SimpleTCPServerAsync(); - //await AsyncTCPConnection2.accept_connections("127.0.0.1", 12345, s, TimeSpan.FromMilliseconds(100)); s.accept(); } - // public static async Task init() - // { - // } - - public void accept() - { + public void accept() { _acceptor.accept_on_port(this, "127.0.0.1", 12345, TimeSpan.Zero); } - public void onConnection(ITCPConnection connection) - { - AsyncTCPConnection2 new_conn = connection as AsyncTCPConnection2; - RemoteConnectionInfo rci = new_conn.get_peer_address(); - _conn_map.Add(rci, new_conn); + public void onConnection(ITCPConnection connection) { + string ip; int port; + connection.getPeerAddress(out ip, out port); + RemoteConnectionInfo rci = new RemoteConnectionInfo(ip, port); + _conn_map.Add(rci, connection); Console.WriteLine($"SimpleTCPServerAsync.onConnection new client connected conn: {rci}"); - new_conn.register(this); + connection.register(this); } - public void onData(RemoteMessage msg) - { + public void onData(RemoteMessage msg) { Console.WriteLine($"SimpleTCPServerAsync.onData msg: {msg}"); RemoteConnectionInfo rci = msg.remoteConnectionInfo; ITCPConnection this_conn; bool found = _conn_map.TryGetValue(rci, out this_conn); - if (!found) - { + if (!found) { Console.WriteLine("Could not find connection !!!!!!"); return; } _n_msgs_received++; Console.WriteLine($"SimpleTCPServerAsync.onData msgs_received: {_n_msgs_received} msg: {msg} ci: {rci} echoing it back"); - if (msg.messageType == RemoteMessageType.Data) - { - + if (msg.messageType == RemoteMessageType.Data) { this_conn.send(msg.message); - // Task.Run(async () => { - // Console.WriteLine($"SimpleTCPServerAsync.onData sending msg: {msg} to client"); - // await _conn.send_async(msg.message); - // }); } } @@ -81,43 +63,4 @@ namespace BCG public void Dispose() { } } - - // public class SimpleTCPServer : ITCPConnectionHandler, ITCPMessageHandler { - // private AsyncTCPConnection2 _conn = null; - // private int _n_msgs_received = 0; - // SingleServerToClientManagedTCPConnectionAcceptor _acceptor = new SingleServerToClientManagedTCPConnectionAcceptor(); - - // public static async Task start() { - // Console.WriteLine("SimpleTCPServer.start accepting socket connections"); - // SimpleTCPServer s = new SimpleTCPServer(); - // s.accept(); - // //await AsyncTCPConnection2.accept_connections("127.0.0.1", 12345, s, TimeSpan.FromMilliseconds(100)); - // } - - // public void accept() { - // _acceptor.accept_on_port(this, "127.0.0.1", 12345, TimeSpan.Zero); - // } - - // public void onConnection(ITCPConnection connection) { - // Console.WriteLine("SimpleTCPServerAsync.onConnection new client connected"); - // _conn = connection as AsyncTCPConnection2; - // connection.register(this); - // } - - // public async void onData(RemoteMessage msg) { - // _n_msgs_received++; - // Console.WriteLine($"SimpleTCPServerAsync.onData msg: {msg} , msgs received: {_n_msgs_received} echoing it back"); - // if (msg.messageType == RemoteMessageType.data && _conn != null) { - // Task.Run(async () => { - // //Console.WriteLine($"SimpleTCPServerAsync.onData sending msg: {msg} to client"); - // //await _conn.send_async(msg.message); - // _conn.send(msg.message); - // }); - // } - // } - - // public bool isDisposed { get { return false; } } - - // public void Dispose() { } - // } } \ No newline at end of file diff --git a/src/DataStreamSuite/PubSub/Testing/SocketEventArgExample.cs b/src/DataStreamSuite/PubSub/Testing/SocketEventArgExample.cs new file mode 100644 index 000000000..e69de29bb diff --git a/src/DataStreamSuite/PubSubServer/Program.cs b/src/DataStreamSuite/PubSubServer/Program.cs index 1a7bc86bf..9d6f7e413 100644 --- a/src/DataStreamSuite/PubSubServer/Program.cs +++ b/src/DataStreamSuite/PubSubServer/Program.cs @@ -15,10 +15,15 @@ namespace BCG { /// [STAThread] public static async Task Main(string[] args) { + bool run_echo_tcp_server_only = true; bts.utils.BTSNativeMethods.provide_command_line(new string[] { }, 0); mbts.config.Configuration.initialize(); - // SimpleTCPServerAsync.start(); - // Task.Delay(1000000000).Wait(); + if (run_echo_tcp_server_only) { + Console.WriteLine("Running as TCP Echo server, Hit key to continue"); + Console.ReadLine(); + await SimpleTCPServerAsync.start(); + Task.Delay(1000000000).Wait(); + } if (args.Length > 0 && args[0] == "daemon") args = args.Skip(1).ToArray();