/// <summary> /// Send a message to the server, asynchronously. /// </summary> /// <param name="data">Data to send to the server.</param> /// <returns>Task with Boolean indicating if the message was sent successfully.</returns> internal async Task <bool> SendAsync(byte[] data) { if (_WtcpClient == null) { if (Debug) { Console.WriteLine("Client is null, cannot send"); } return(false); } if (_WtcpClient.Connected) { await _WtcpClient.SendAsync(data); return(true); } else { if (Debug) { Console.WriteLine("Client is not connected, cannot send"); } return(false); } }
async Task connect() { retry: try { close_connection(); client = new WatsonTcpClient(xip.address, xip.port + 1); client.Events.MessageReceived += Events_MessageReceived; await Task.Run(client.Connect); byte[] bfr = new byte[10]; p_crypto.random.NextBytes(bfr); var key = a.api2.c_key; bfr = p_crypto.Encrypt(bfr, key); m_packet data = new() { data = bfr, deviceid = key.id, }; bfr = p_crypto.convert(data); await client.SendAsync(bfr); time = DateTime.Now; } catch { goto retry; } }
internal async Task <bool> SendAsync(Dictionary <object, object> metadata, long contentLength, Stream stream) { if (contentLength < 0) { throw new ArgumentException("Content length must be zero or greater."); } if (stream == null || !stream.CanRead) { throw new ArgumentException("Cannot read from supplied stream."); } if (_WtcpClient == null) { Logger?.Invoke("[ClusterClient] Client is null, cannot send"); return(false); } if (_WtcpClient.Connected) { return(await _WtcpClient.SendAsync(metadata, contentLength, stream)); } else { Logger?.Invoke("[ClusterClient] Client is not connected, cannot send"); return(false); } }
/// <summary> /// Send a message to the server, asynchronously. /// </summary> /// <param name="data">Data to send to the server.</param> /// <returns>Task with Boolean indicating if the message was sent successfully.</returns> public async Task <bool> SendAsync(byte[] data) { if (Wtcp == null) { if (Debug) { Console.WriteLine("Client is null, cannot send"); } return(false); } if (Wtcp.IsConnected()) { await Wtcp.SendAsync(data); return(true); } else { if (Debug) { Console.WriteLine("Client is not connected, cannot send"); } return(false); } }
internal async Task <bool> Send(long contentLength, Stream stream) { if (contentLength < 0) { throw new ArgumentException("Content length must be zero or greater."); } if (stream == null || !stream.CanRead) { throw new ArgumentException("Cannot read from supplied stream."); } if (_WtcpClient == null) { if (Debug) { Log("Client is null, cannot send"); } return(false); } if (_WtcpClient.Connected) { return(await _WtcpClient.SendAsync(contentLength, stream)); } else { if (Debug) { Log("Client is not connected, cannot send"); } return(false); } }
internal async Task <bool> SendAsync(byte[] data) { if (data == null || data.Length < 1) { throw new ArgumentNullException(nameof(data)); } try { return(await _TcpClient.SendAsync(data)); } catch (Exception e) { Logger?.Invoke("[MeshClient] SendAsync exception: " + Environment.NewLine + Common.SerializeJson(e, true)); return(false); } }
/// <summary> /// Send data to the remote server. /// </summary> /// <param name="data">Byte data to send.</param> /// <returns>True if successful.</returns> public async Task <bool> Send(byte[] data) { if (data == null || data.Length < 1) { throw new ArgumentNullException(nameof(data)); } try { return(await _TcpClient.SendAsync(data)); } catch (Exception e) { if (Debug) { Console.WriteLine(Common.SerializeJson(e, true)); } return(false); } }
public void JoinServer(string name, string color) { var checkUser = Users.Find(existingUser => existingUser.Name.Equals(name)); if (checkUser != null) { throw new UserAlreadyExistsException(name); } var user = new User { Name = name, Color = color }; var payload = new JoinPayload(user.Name, user.Color); var serverPacket = new ServerPacket(ServerAction.Join, payload); _client.Connect(); _client.SendAsync(serverPacket.ToJson()); InvokeServerJoinEvent(); }
public async Task SendRequest(APIConnect.Request request) { logger.Warn("Sending request " + request); logger.Warn("Is client connected? " + client.IsConnected()); // If client isn't connected, no point in trying to send if (!client.IsConnected()) { logger.Warn("Could not send request. Client is not connected."); return; } bool val = await client.SendAsync(Encoding.ASCII.GetBytes(request.command)); logger.Warn("Output " + val); }
private async void Test2ClientWorker(int clientNum) { try { long msgsSent = 0; long bytesSent = 0; using (WatsonTcpClient client = new WatsonTcpClient("127.0.0.1", 10000)) { client.Events.MessageReceived += Test2ClientMsgRcv; client.Connect(); for (int i = 0; i < _NumMessages; i++) { bool success = await client.SendAsync(_MsgBytes); if (success) { msgsSent++; bytesSent += _MsgBytes.Length; Interlocked.Increment(ref _MessagesSentSuccess); Interlocked.Increment(ref _MessagesProcessing); Interlocked.Add(ref _BytesSent, _MsgBytes.Length); } else { Interlocked.Increment(ref _MessagesSentFailed); } } } Interlocked.Decrement(ref _RunningTasks); Console.WriteLine("Client " + clientNum + " finished, sent " + msgsSent + " messages, " + bytesSent + " bytes"); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); } }
async void Events_MessageReceived(object sender, MessageReceivedEventArgs e) { if (e.Data.Length == 1) { e_pulse pulse = (e_pulse)e.Data[0]; if (pulse == e_pulse.s_live) { time = DateTime.Now; if (!reset) { a.c_notify.reset(xid); reset = true; } } else { throw new Exception("kdvjfjhsjcjfndj"); } } else { var dv = p_crypto.convert <m_notify>(e.Data); if (dv.xid != xid) { throw new Exception("ldkjjnjgnhdhvhgnbjf"); } if (dv.userid == null) { throw new Exception("kfjvjdvjfhfhshvfdhf"); } time = DateTime.Now; a.c_notify.c_notify(dv); } await Task.Delay(1000); await client.SendAsync(new byte[] { (byte)e_pulse.c_live }); }
private static void Main(string[] args) { InitializeClient(); bool runForever = true; Dictionary <object, object> metadata; bool success; while (runForever) { string userInput = InputString("Command [? for help]:", null, false); switch (userInput) { case "?": Console.WriteLine("Available commands:"); Console.WriteLine(" ? help (this menu)"); Console.WriteLine(" q quit"); Console.WriteLine(" cls clear screen"); Console.WriteLine(" send send message to server"); Console.WriteLine(" send offset send message to server with offset"); Console.WriteLine(" send md send message with metadata to server"); Console.WriteLine(" sendasync send message to server asynchronously"); Console.WriteLine(" sendasync md send message with metadata to server asynchronously"); Console.WriteLine(" sendandwait send message and wait for a response"); Console.WriteLine(" sendempty send empty message with metadata"); Console.WriteLine(" sendandwait empty send empty message with metadata and wait for a response"); Console.WriteLine(" status show if client connected"); Console.WriteLine(" dispose dispose of the client"); Console.WriteLine(" connect connect to the server"); Console.WriteLine(" disconnect disconnect from the server"); Console.WriteLine(" psk set the preshared key"); Console.WriteLine(" auth authenticate using the preshared key"); Console.WriteLine(" stats display client statistics"); Console.WriteLine(" stats reset reset statistics other than start time and uptime"); Console.WriteLine(" debug enable/disable debug"); break; case "q": runForever = false; break; case "cls": Console.Clear(); break; case "send": userInput = InputString("Data:", null, false); if (!_Client.Send(Encoding.UTF8.GetBytes(userInput))) { Console.WriteLine("Failed"); } break; case "send offset": userInput = InputString("Data:", null, false); int offset = InputInteger("Offset:", 0, true, true); if (!_Client.Send(Encoding.UTF8.GetBytes(userInput), null, offset)) { Console.WriteLine("Failed"); } break; case "send md": userInput = InputString("Data:", null, false); metadata = InputDictionary(); if (!_Client.Send(Encoding.UTF8.GetBytes(userInput), metadata)) { Console.WriteLine("Failed"); } break; case "send md large": metadata = new Dictionary <object, object>(); for (int i = 0; i < 100000; i++) { metadata.Add(i, i); } if (!_Client.Send("Hello!", metadata)) { Console.WriteLine("Failed"); } break; case "sendasync": userInput = InputString("Data:", null, false); success = _Client.SendAsync(Encoding.UTF8.GetBytes(userInput)).Result; if (!success) { Console.WriteLine("Failed"); } break; case "sendasync md": userInput = InputString("Data:", null, false); metadata = InputDictionary(); success = _Client.SendAsync(Encoding.UTF8.GetBytes(userInput), metadata).Result; if (!success) { Console.WriteLine("Failed"); } break; case "sendandwait": SendAndWait(); break; case "sendempty": metadata = InputDictionary(); success = _Client.Send("", metadata); if (!success) { Console.WriteLine("Failed"); } break; case "sendandwait empty": SendAndWaitEmpty(); break; case "status": if (_Client == null) { Console.WriteLine("Connected: False (null)"); } else { Console.WriteLine("Connected: " + _Client.Connected); } break; case "dispose": _Client.Dispose(); break; case "connect": _Client.Connect(); break; case "disconnect": _Client.Disconnect(); break; case "psk": _PresharedKey = InputString("Preshared key:", "1234567812345678", false); break; case "auth": _Client.Authenticate(_PresharedKey); break; case "stats": Console.WriteLine(_Client.Statistics.ToString()); break; case "stats reset": _Client.Statistics.Reset(); break; case "debug": _Client.Settings.DebugMessages = !_Client.Settings.DebugMessages; Console.WriteLine("Debug set to: " + _Client.Settings.DebugMessages); break; default: break; } } }
public void SendMessage(string message) { _client?.SendAsync(Encoding.UTF8.GetBytes(message)); }
private static void Main(string[] args) { serverIp = InputString("Server IP:", "127.0.0.1", false); serverPort = InputInteger("Server port:", 9000, true, false); useSsl = InputBoolean("Use SSL:", false); InitializeClient(); bool runForever = true; Dictionary <object, object> metadata; bool success; while (runForever) { Console.Write("Command [? for help]: "); string userInput = Console.ReadLine(); byte[] data = null; MemoryStream ms = null; if (String.IsNullOrEmpty(userInput)) { continue; } switch (userInput) { case "?": Console.WriteLine("Available commands:"); Console.WriteLine(" ? help (this menu)"); Console.WriteLine(" q quit"); Console.WriteLine(" cls clear screen"); Console.WriteLine(" send send message to server"); Console.WriteLine(" send md send message with metadata to server"); Console.WriteLine(" sendasync send message to server asynchronously"); Console.WriteLine(" sendasync md send message with metadata to server asynchronously"); Console.WriteLine(" sendandwait send message and wait for a response"); Console.WriteLine(" status show if client connected"); Console.WriteLine(" dispose dispose of the client"); Console.WriteLine(" connect connect to the server"); Console.WriteLine(" disconnect disconnect from the server"); Console.WriteLine(" psk set the preshared key"); Console.WriteLine(" auth authenticate using the preshared key"); Console.WriteLine(" debug enable/disable debug"); break; case "q": runForever = false; break; case "cls": Console.Clear(); break; case "send": Console.Write("Data: "); userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { break; } data = Encoding.UTF8.GetBytes(userInput); ms = new MemoryStream(data); success = client.Send(data.Length, ms); Console.WriteLine(success); break; case "send md": metadata = InputDictionary(); Console.Write("Data: "); userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { break; } data = Encoding.UTF8.GetBytes(userInput); ms = new MemoryStream(data); success = client.Send(data.Length, ms, metadata); Console.WriteLine(success); break; case "sendasync": Console.Write("Data: "); userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { break; } data = Encoding.UTF8.GetBytes(userInput); ms = new MemoryStream(data); success = client.SendAsync(data.Length, ms).Result; Console.WriteLine(success); break; case "sendasync md": metadata = InputDictionary(); Console.Write("Data: "); userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { break; } data = Encoding.UTF8.GetBytes(userInput); ms = new MemoryStream(data); success = client.SendAsync(data.Length, ms, metadata).Result; Console.WriteLine(success); break; case "sendandwait": SendAndWait(); break; case "status": if (client == null) { Console.WriteLine("Connected: False (null)"); } else { Console.WriteLine("Connected: " + client.Connected); } break; case "dispose": client.Dispose(); break; case "connect": client.Connect(); break; case "disconnect": client.Disconnect(); break; case "psk": presharedKey = InputString("Preshared key:", "1234567812345678", false); break; case "auth": client.Authenticate(presharedKey); break; case "debug": client.Settings.DebugMessages = !client.Settings.DebugMessages; Console.WriteLine("Debug set to: " + client.Settings.DebugMessages); break; default: break; } } }
static void Main(string[] args) { serverIp = Common.InputString("Server IP:", "127.0.0.1", false); serverPort = Common.InputInteger("Server port:", 9000, true, false); useSsl = Common.InputBoolean("Use SSL:", false); InitializeClient(); bool runForever = true; while (runForever) { Console.Write("Command [? for help]: "); string userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { continue; } switch (userInput) { case "?": Console.WriteLine("Available commands:"); Console.WriteLine(" ? help (this menu)"); Console.WriteLine(" q quit"); Console.WriteLine(" cls clear screen"); Console.WriteLine(" send send message to server"); Console.WriteLine(" sendasync send message to server asynchronously"); Console.WriteLine(" status show if client connected"); Console.WriteLine(" dispose dispose of the connection"); Console.WriteLine(" connect connect to the server if not connected"); Console.WriteLine(" reconnect disconnect if connected, then reconnect"); Console.WriteLine(" psk set the preshared key"); Console.WriteLine(" auth authenticate using the preshared key"); Console.WriteLine(" debug enable/disable debug (currently " + client.Debug + ")"); break; case "q": runForever = false; break; case "cls": Console.Clear(); break; case "send": Console.Write("Data: "); userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { break; } client.Send(Encoding.UTF8.GetBytes(userInput)); break; case "sendasync": Console.Write("Data: "); userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { break; } bool success = client.SendAsync(Encoding.UTF8.GetBytes(userInput)).Result; break; case "status": if (client == null) { Console.WriteLine("Connected: False (null)"); } else { Console.WriteLine("Connected: " + client.Connected); } break; case "dispose": client.Dispose(); break; case "connect": if (client != null && client.Connected) { Console.WriteLine("Already connected"); } else { client = new WatsonTcpClient(serverIp, serverPort); client.ServerConnected = ServerConnected; client.ServerDisconnected = ServerDisconnected; client.MessageReceived = MessageReceived; client.Start(); } break; case "reconnect": if (client != null) { client.Dispose(); } client = new WatsonTcpClient(serverIp, serverPort); client.ServerConnected = ServerConnected; client.ServerDisconnected = ServerDisconnected; client.MessageReceived = MessageReceived; client.Start(); break; case "psk": presharedKey = Common.InputString("Preshared key:", "1234567812345678", false); break; case "auth": client.Authenticate(presharedKey); break; case "debug": client.Debug = !client.Debug; Console.WriteLine("Debug set to: " + client.Debug); break; default: break; } } }
private static void Main(string[] args) { InitializeClient(); bool runForever = true; Dictionary <object, object> metadata; bool success; while (runForever) { string userInput = InputString("Command [? for help]:", null, false); switch (userInput) { case "?": Console.WriteLine("Available commands:"); Console.WriteLine(" ? help (this menu)"); Console.WriteLine(" q quit"); Console.WriteLine(" cls clear screen"); Console.WriteLine(" send send message to server"); Console.WriteLine(" send md send message with metadata to server"); Console.WriteLine(" sendasync send message to server asynchronously"); Console.WriteLine(" sendasync md send message with metadata to server asynchronously"); Console.WriteLine(" sendandwait send message and wait for a response"); Console.WriteLine(" sendempty send empty message with metadata"); Console.WriteLine(" sendandwait empty send empty message with metadata and wait for a response"); Console.WriteLine(" status show if client connected"); Console.WriteLine(" dispose dispose of the connection"); Console.WriteLine(" connect connect to the server if not connected"); Console.WriteLine(" reconnect disconnect if connected, then reconnect"); Console.WriteLine(" psk set the preshared key"); Console.WriteLine(" auth authenticate using the preshared key"); Console.WriteLine(" stats display client statistics"); Console.WriteLine(" stats reset reset statistics other than start time and uptime"); Console.WriteLine(" comp set the compression type, currently: " + client.Compression.ToString()); Console.WriteLine(" debug enable/disable debug (currently " + client.DebugMessages + ")"); break; case "q": runForever = false; break; case "cls": Console.Clear(); break; case "send": userInput = InputString("Data:", null, false); if (!client.Send(Encoding.UTF8.GetBytes(userInput))) { Console.WriteLine("Failed"); } break; case "send md": userInput = InputString("Data:", null, false); metadata = InputDictionary(); if (!client.Send(metadata, Encoding.UTF8.GetBytes(userInput))) { Console.WriteLine("Failed"); } break; case "send md large": metadata = new Dictionary <object, object>(); for (int i = 0; i < 100000; i++) { metadata.Add(i, i); } if (!client.Send(metadata, "Hello!")) { Console.WriteLine("Failed"); } break; case "sendasync": userInput = InputString("Data:", null, false); success = client.SendAsync(Encoding.UTF8.GetBytes(userInput)).Result; if (!success) { Console.WriteLine("Failed"); } break; case "sendasync md": userInput = InputString("Data:", null, false); metadata = InputDictionary(); success = client.SendAsync(metadata, Encoding.UTF8.GetBytes(userInput)).Result; if (!success) { Console.WriteLine("Failed"); } break; case "sendandwait": SendAndWait(); break; case "sendempty": metadata = InputDictionary(); success = client.Send(metadata); if (!success) { Console.WriteLine("Failed"); } break; case "sendandwait empty": SendAndWaitEmpty(); break; case "status": if (client == null) { Console.WriteLine("Connected: False (null)"); } else { Console.WriteLine("Connected: " + client.Connected); } break; case "dispose": client.Dispose(); break; case "connect": if (client != null && client.Connected) { Console.WriteLine("Already connected"); } else { client = new WatsonTcpClient(serverIp, serverPort); client.ServerConnected += ServerConnected; client.ServerDisconnected += ServerDisconnected; client.MessageReceived += MessageReceived; client.Start(); } break; case "reconnect": ConnectClient(); break; case "psk": presharedKey = InputString("Preshared key:", "1234567812345678", false); break; case "auth": client.Authenticate(presharedKey); break; case "stats": Console.WriteLine(client.Stats.ToString()); break; case "stats reset": client.Stats.Reset(); break; case "comp": client.Compression = (CompressionType)(Enum.Parse(typeof(CompressionType), InputString("Compression [None|Default|Gzip]:", "None", false))); break; case "debug": client.DebugMessages = !client.DebugMessages; Console.WriteLine("Debug set to: " + client.DebugMessages); break; default: break; } } }
internal async void RunTest() { try { using (WatsonTcpServer server = new WatsonTcpServer("127.0.0.1", 10000)) { server.Events.MessageReceived += Test1ServerMsgRcv; server.Start(); // server.Settings.Logger = ServerLogger; // server.Debug = true; using (WatsonTcpClient client = new WatsonTcpClient("127.0.0.1", 10000)) { client.Events.MessageReceived += Test1ClientMsgRcv; client.Connect(); _Stopwatch.Start(); for (int i = 0; i < _NumMessages; i++) { bool success = await client.SendAsync(_MsgBytes); if (success) { Interlocked.Increment(ref _MessagesSentSuccess); Interlocked.Increment(ref _MessagesProcessing); Interlocked.Add(ref _BytesSent, _MessageSize); } else { Interlocked.Increment(ref _MessagesSentFailed); } } _Stopwatch.Stop(); decimal secondsTotal = _Stopwatch.ElapsedMilliseconds / 1000; if (secondsTotal < 1) { secondsTotal = 1; } Console.WriteLine("Messages sent after " + secondsTotal + " seconds"); while (_MessagesProcessing > 0) { Console.WriteLine("Waiting on " + _MessagesProcessing + " to complete processing (1 second pause)"); Thread.Sleep(1000); } Console.WriteLine(""); Console.WriteLine("Results:"); Console.WriteLine(" Messages sent successfully : " + _MessagesSentSuccess); Console.WriteLine(" Messages failed : " + _MessagesSentFailed); Console.WriteLine(" Bytes sent successfully : " + _BytesSent); Console.WriteLine(" Bytes received successfully : " + _BytesReceived); decimal bytesPerSecond = _BytesSent / secondsTotal; decimal kbPerSecond = bytesPerSecond / 1024; decimal mbPerSecond = kbPerSecond / 1024; Console.WriteLine(" Elapsed time sending (ms) : " + _Stopwatch.ElapsedMilliseconds + "ms"); Console.WriteLine(" Elapsed time sending (seconds) : " + decimal.Round(secondsTotal, 2) + "s"); Console.WriteLine(" Send bytes per second : " + decimal.Round(bytesPerSecond, 2) + "B/s"); Console.WriteLine(" Send kilobytes per second : " + decimal.Round(kbPerSecond, 2) + "kB/s"); Console.WriteLine(" Send megabytes per second : " + decimal.Round(mbPerSecond, 2) + "MB/s"); Console.WriteLine(""); } } } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); } }
static void Main(string[] args) { Console.Write("Server IP : "); serverIp = Console.ReadLine(); Console.Write("Server Port : "); serverPort = Convert.ToInt32(Console.ReadLine()); WatsonTcpClient client = new WatsonTcpClient(serverIp, serverPort, ServerConnected, ServerDisconnected, MessageReceived, true); bool runForever = true; while (runForever) { Console.Write("Command [? for help]: "); string userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { continue; } switch (userInput) { case "?": Console.WriteLine("Available commands:"); Console.WriteLine(" ? help (this menu)"); Console.WriteLine(" q quit"); Console.WriteLine(" cls clear screen"); Console.WriteLine(" send send message to server"); Console.WriteLine(" sendasync send message to server asynchronously"); Console.WriteLine(" status show if client connected"); Console.WriteLine(" dispose dispose of the connection"); Console.WriteLine(" connect connect to the server if not connected"); Console.WriteLine(" reconnect disconnect if connected, then reconnect"); break; case "q": runForever = false; break; case "cls": Console.Clear(); break; case "send": Console.Write("Data: "); userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { break; } client.Send(Encoding.UTF8.GetBytes(userInput)); break; case "sendasync": Console.Write("Data: "); userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { break; } client.SendAsync(Encoding.UTF8.GetBytes(userInput)); break; case "status": if (client == null) { Console.WriteLine("Connected: False (null)"); } else { Console.WriteLine("Connected: " + client.IsConnected()); } break; case "dispose": client.Dispose(); break; case "connect": if (client != null && client.IsConnected()) { Console.WriteLine("Already connected"); } else { client = new WatsonTcpClient(serverIp, serverPort, ServerConnected, ServerDisconnected, MessageReceived, true); } break; case "reconnect": if (client != null) { client.Dispose(); } client = new WatsonTcpClient(serverIp, serverPort, ServerConnected, ServerDisconnected, MessageReceived, true); break; default: break; } } }