public static async Task <Object> SendRequestAsync(Object subrequest, RequestType type, ResponseType resptype) { if (!client.Connected) { return(null); } if (connectionTimeout.Elapsed.TotalSeconds > 300) { Disconnect(); await Connect(); } Request request = new Request() { Username = SettingsManager.Username, Content = subrequest, SessionId = SettingsManager.AuthKey, Type = type }; string message = JsonConvert.SerializeObject(request); try { NetworkStream serverStream = client.GetStream(); byte[] buffer = Encoding.UTF8.GetBytes(message); serverStream.Write(buffer, 0, buffer.Length); } catch (Exception) { AppNotificationManager.PushMessage(new AppNotification() { Message = "Connection Error. Reconnect." }); } return(await GetResponse(resptype)); }
public async static Task <bool> Connect() { try { client = new TcpClient(); await client.ConnectAsync(serverAddress, portAddress); connectionTimeout.Start(); } catch (Exception) { } AppNotificationManager.PushMessage(new AppNotification() { Message = String.Format("Server Connected : {0} ", client.Connected) }); return(client.Connected); }
private static async Task <Object> GetResponse(ResponseType resptype, bool useDefault = true) { TcpClient server = client; if (!useDefault) { server = _backupClient; } string message = ""; try { var serverStream = server.GetStream(); serverStream.ReadTimeout = 10000; byte[] receiveBuffer = new byte[65536]; await serverStream.ReadAsync(receiveBuffer, 0, 65535); message = Encoding.UTF8.GetString(receiveBuffer).Trim('\0'); Response resp = JsonConvert.DeserializeObject <Response>(message); if (resp.Type == resptype) { connectionTimeout.Restart(); return(resp.Content); } else { return(null); } } catch (Exception) { if (useDefault) //sends message in case default connection is not responding <- exception to upload connection. { AppNotificationManager.PushMessage(new AppNotification() { Message = "No Response From Server." }); } } return(null); }