private async Task <ClusterMaintenanceConnection> ConnectToClientNodeAsync(TcpConnectionInfo tcpConnectionInfo, TimeSpan timeout) { TcpConnectionHeaderMessage.SupportedFeatures supportedFeatures; Stream connection; TcpClient tcpClient; using (_contextPool.AllocateOperationContext(out JsonOperationContext ctx)) { var result = await TcpUtils.ConnectSecuredTcpSocket( tcpConnectionInfo, _parent._server.Server.Certificate.Certificate, _parent._server.Server.CipherSuitesPolicy, TcpConnectionHeaderMessage.OperationTypes.Heartbeats, NegotiateProtocolVersionAsyncForClusterSupervisor, ctx, timeout, null, _token); tcpClient = result.TcpClient; connection = result.Stream; supportedFeatures = result.SupportedFeatures; await using (var writer = new AsyncBlittableJsonTextWriter(ctx, connection)) { await WriteClusterMaintenanceConnectionHeaderAsync(writer); } } return(new ClusterMaintenanceConnection { TcpClient = tcpClient, Stream = connection, SupportedFeatures = supportedFeatures }); }
private async Task <ClusterMaintenanceConnection> ConnectToClientNodeAsync(TcpConnectionInfo tcpConnectionInfo, TimeSpan timeout) { TcpConnectionHeaderMessage.SupportedFeatures supportedFeatures; var tcpClient = await TcpUtils.ConnectSocketAsync(tcpConnectionInfo, timeout, _log); var connection = await TcpUtils.WrapStreamWithSslAsync(tcpClient, tcpConnectionInfo, _parent._server.Server.Certificate.Certificate, timeout); using (_contextPool.AllocateOperationContext(out JsonOperationContext ctx)) using (var writer = new BlittableJsonTextWriter(ctx, connection)) { var paramaters = new TcpNegotiateParamaters { Database = null, Operation = TcpConnectionHeaderMessage.OperationTypes.Heartbeats, Version = TcpConnectionHeaderMessage.HeartbeatsTcpVersion, ReadResponseAndGetVersionAsync = SupervisorReadResponseAndGetVersionAsync, Url = tcpConnectionInfo.Url }; supportedFeatures = await TcpNegotiation.NegotiateProtocolVersionAsync(ctx, connection, paramaters).ConfigureAwait(false); WriteClusterMaintenanceConnectionHeader(writer); } return(new ClusterMaintenanceConnection { TcpClient = tcpClient, Stream = connection, SupportedFeatures = supportedFeatures }); }
public void Receive() { while (true) { // blocking call TcpClient client = _tcpServer.AcceptTcpClient(); Thread clientThread = new Thread(() => { String command = TcpUtils.ReceiveCommand(client, Constants.TRANSFER_TCP_FILE.Length); if (command.Equals(Constants.TRANSFER_TCP_FILE)) { ReceiveFile(client); } else { ReceiveDirectory(client); } client.Close(); }); clientThread.IsBackground = true; clientThread.SetApartmentState(ApartmentState.STA); clientThread.Start(); } }
private void SendDirectoryFile(TcpClient tcpClient, string filePath) { TcpUtils.SendFileRequest(tcpClient); SendFileNodeDescription(tcpClient, filePath); string responseCommand; try { responseCommand = TcpUtils.ReceiveCommand(tcpClient, Constants.TRANSFER_TCP_ACCEPT.Length); } catch (Exception e) { MessageBox.Show("Timeout waiting for user response", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (!responseCommand.Equals(Constants.TRANSFER_TCP_ACCEPT)) { ManageRefusedFile(filePath); return; } SendFileContent(tcpClient, filePath); }
private static void Main(string[] args) { System.Console.WriteLine("Silverlight and Flash Prolicy Server Copyright @ henryfan 2012"); System.Console.WriteLine("website:www.ikender.com"); System.Console.WriteLine("email:[email protected]"); try { TcpUtils.Setup("beetle"); if (ProlicySection.Instance.FlashEnabled) { new Program { Type = Program.ProlicyType.Flash }.Open(ProlicySection.Instance.FlashPort); System.Console.WriteLine("Start Flash Prolicy Server @" + ProlicySection.Instance.FlashPort); } if (ProlicySection.Instance.SLEnabled) { new Program { Type = Program.ProlicyType.Silverlight }.Open(ProlicySection.Instance.SLPort); System.Console.WriteLine("Start Silverlight Prolicy Server @" + ProlicySection.Instance.SLPort); } } catch (Exception e_) { Console.WriteLine(e_.Message); } System.Threading.Thread.Sleep(-1); }
private async Task <(TcpClient TcpClient, Stream Connection)> ConnectToClientNodeAsync(TcpConnectionInfo tcpConnectionInfo, TimeSpan timeout) { var tcpClient = await TcpUtils.ConnectSocketAsync(tcpConnectionInfo, timeout, _log); var connection = await TcpUtils.WrapStreamWithSslAsync(tcpClient, tcpConnectionInfo, _parent._server.RavenServer.ClusterCertificateHolder.Certificate); using (_contextPool.AllocateOperationContext(out JsonOperationContext ctx)) using (var writer = new BlittableJsonTextWriter(ctx, connection)) { WriteOperationHeaderToRemote(writer); using (var responseJson = await ctx.ReadForMemoryAsync(connection, _readStatusUpdateDebugString + "/Read-Handshake-Response", _token)) { var headerResponse = JsonDeserializationServer.TcpConnectionHeaderResponse(responseJson); switch (headerResponse.Status) { case TcpConnectionStatus.Ok: break; case TcpConnectionStatus.AuthorizationFailed: throw new UnauthorizedAccessException( $"Node with ClusterTag = {ClusterTag} replied to initial handshake with authorization failure {headerResponse.Message}"); case TcpConnectionStatus.TcpVersionMissmatch: throw new InvalidOperationException($"Node with ClusterTag = {ClusterTag} replied to initial handshake with missmatching tcp version {headerResponse.Message}"); } } WriteClusterMaintenanceConnectionHeader(writer); } return(tcpClient, connection); }
private async Task <ClusterMaintenanceConnection> ConnectToClientNodeAsync(TcpConnectionInfo tcpConnectionInfo, TimeSpan timeout) { TcpConnectionHeaderMessage.SupportedFeatures supportedFeatures; TcpClient tcpClient; string url; (tcpClient, url) = await TcpUtils.ConnectSocketAsync(tcpConnectionInfo, timeout, _log); var connection = await TcpUtils.WrapStreamWithSslAsync(tcpClient, tcpConnectionInfo, _parent._server.Server.Certificate.Certificate, _parent._server.Server.CipherSuitesPolicy, timeout); using (_contextPool.AllocateOperationContext(out JsonOperationContext ctx)) using (var writer = new BlittableJsonTextWriter(ctx, connection)) { var parameters = new TcpNegotiateParameters { Database = null, Operation = TcpConnectionHeaderMessage.OperationTypes.Heartbeats, Version = TcpConnectionHeaderMessage.HeartbeatsTcpVersion, ReadResponseAndGetVersionCallback = SupervisorReadResponseAndGetVersion, DestinationUrl = url, DestinationNodeTag = ClusterTag }; supportedFeatures = TcpNegotiation.NegotiateProtocolVersion(ctx, connection, parameters); WriteClusterMaintenanceConnectionHeader(writer); } return(new ClusterMaintenanceConnection { TcpClient = tcpClient, Stream = connection, SupportedFeatures = supportedFeatures }); }
private async Task <(TcpClient TcpClient, Stream Connection)> ConnectAndGetNetworkStreamAsync(TcpConnectionInfo tcpConnectionInfo, TimeSpan timeout, Logger log) { var tcpClient = await TcpUtils.ConnectSocketAsync(tcpConnectionInfo, timeout, log); var connection = await TcpUtils.WrapStreamWithSslAsync(tcpClient, tcpConnectionInfo, Server.ClusterCertificateHolder.Certificate); return(tcpClient, connection); }
public static async Task ConnectToClientNodeAsync(RavenServer server, TcpConnectionInfo tcpConnectionInfo, TimeSpan timeout, Logger log, string database, NodeConnectionTestResult result, CancellationToken token = default) { List <string> negLogs = new(); using (server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext ctx)) { using var tcpSocketResult = await TcpUtils.ConnectSecuredTcpSocket(tcpConnectionInfo, server.Certificate.Certificate, server.CipherSuitesPolicy, TcpConnectionHeaderMessage.OperationTypes.TestConnection, NegotiateWithRemote, ctx, timeout, negLogs, token); } result.Log = negLogs; async Task <TcpConnectionHeaderMessage.SupportedFeatures> NegotiateWithRemote(string url, TcpConnectionInfo info, Stream stream, JsonOperationContext context, List <string> logs = null) { await using (var writer = new AsyncBlittableJsonTextWriter(context, stream)) { await WriteOperationHeaderToRemote(writer, TcpConnectionHeaderMessage.OperationTypes.TestConnection, database, info.ServerId); using (var responseJson = await context.ReadForMemoryAsync(stream, $"TestConnectionHandler/{url}/Read-Handshake-Response")) { var headerResponse = JsonDeserializationServer.TcpConnectionHeaderResponse(responseJson); switch (headerResponse.Status) { case TcpConnectionStatus.Ok: result.Success = true; result.Error = null; logs?.Add($"Successfully negotiated with {url}."); break; case TcpConnectionStatus.AuthorizationFailed: result.Success = false; result.Error = $"Connection to {url} failed because of authorization failure: {headerResponse.Message}"; logs?.Add(result.Error); throw new AuthorizationException(result.Error); case TcpConnectionStatus.TcpVersionMismatch: result.Success = false; result.Error = $"Connection to {url} failed because of mismatching tcp version: {headerResponse.Message}"; logs?.Add(result.Error); await WriteOperationHeaderToRemote(writer, TcpConnectionHeaderMessage.OperationTypes.Drop, database, info.ServerId); throw new AuthorizationException(result.Error); case TcpConnectionStatus.InvalidNetworkTopology: result.Success = false; result.Error = $"Connection to {url} failed because of {nameof(TcpConnectionStatus.InvalidNetworkTopology)} error: {headerResponse.Message}"; logs?.Add(result.Error); throw new InvalidNetworkTopologyException(result.Error); } } } return(null); } }
private void ReceiveFile(TcpClient client) { // receive file name String jsonFileNode = TcpUtils.ReceiveDescription(client); FileNode fileNode = JsonConvert.DeserializeObject <FileNode>(jsonFileNode); String destinationDir = CheckDict(client, fileNode); if (destinationDir != null) { if (!Properties.Settings.Default.AutoAccept) { InterfaceUtils.ShowMainWindow(false); } ReceiveDirectoryFile(client, fileNode, destinationDir); } else { // retrieveing destination dir if (Properties.Settings.Default.AutoAccept) { TcpUtils.SendAcceptanceResponse(client); // default dir destinationDir = Properties.Settings.Default.DefaultDir; } else { // asking user for file acceptance UI.FilesAcceptance fileAcceptanceWindow = new UI.FilesAcceptance(fileNode); // blocking call until window is closed fileAcceptanceWindow.ShowDialog(); if (fileAcceptanceWindow.AreFilesAccepted) { // file accepted TcpUtils.SendAcceptanceResponse(client); destinationDir = fileAcceptanceWindow.DestinationDir; InterfaceUtils.ShowMainWindow(false); } else { // file not accepted or window closed TcpUtils.SendRefuseResponse(client); return; } } ReceiveFileContent(client, fileNode, destinationDir); } }
static void Main(string[] args) { Console.WriteLine(Beetle.LICENSE.GetLICENSE()); Beetle.WebSockets.Controllers.Controller.Register(new Handler()); TcpUtils.Setup("beetle"); Program server = new Program(); server.Open(8089); Console.WriteLine("websocket start@8089"); Console.Read(); }
private bool ReceiveDirectoryFile(TcpClient tcpClient, FileNode fileNode, string destinationDir) { TcpUtils.SendAcceptanceResponse(tcpClient); IPEndPoint client = (IPEndPoint)tcpClient.Client.RemoteEndPoint; IPAddress addr = client.Address; acceptedFiles[addr].Remove(fileNode); return(ReceiveFileContent(tcpClient, fileNode, destinationDir)); }
private void FrmMain_Load(object sender, EventArgs e) { Beetle.Controllers.Controller.Register(this); TcpUtils.Setup("beetle"); mSumChat.Append(@"{\rtf1\ansi\ansicpg936\deff0\deflang1033\deflangfe2052{\fonttbl{\f0\fnil\fcharset134 \'cb\'ce\'cc\'e5;}}"); mSumChat.Append(@"{\colortbl ;\red51\green153\blue255;}"); LoadFace(); AddFace(); richSay.Focus(); }
public override async Task <Stream> ConnectToPeer(string url, X509Certificate2 certificate) { TimeSpan time; using (ContextPoolForReadOnlyOperations.AllocateOperationContext(out TransactionOperationContext ctx)) using (ctx.OpenReadTransaction()) { time = _parent.ElectionTimeout * (_parent.GetTopology(ctx).AllNodes.Count - 2); } var tcpClient = await TcpUtils.ConnectAsync(url, time); return(tcpClient.GetStream()); }
private DirectoryNode SendDirectoryNodeDescription(TcpClient tcpClient) { // preparing directory node DirectoryNode directoryNode = FilesUtils.BuildDirectoryNode(_path); directoryNode.SenderUserName = Properties.Settings.Default.Name; // sending directory node description string jsonDirectoryNodeDescription = JsonConvert.SerializeObject(directoryNode); TcpUtils.SendDescription(tcpClient, jsonDirectoryNodeDescription); return(directoryNode); }
private void btnSend_Click(object sender, EventArgs e) { var message = tbMessage.Text; if (string.IsNullOrWhiteSpace(message)) { MessageBox.Show(this, "Сообщение не может быть пустым", "Некорректные параметры", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } TcpUtils.SendMessage(message, tcpSender.GetStream()); }
private async Task <PingResult> PingOnce(string url) { var sp = Stopwatch.StartNew(); var result = new PingResult { Url = url }; try { using (var cts = new CancellationTokenSource(ServerStore.Engine.TcpConnectionTimeout)) { var info = await ReplicationUtils.GetTcpInfoAsync(url, null, "PingTest", ServerStore.Engine.ClusterCertificate, cts.Token); result.TcpInfoTime = sp.ElapsedMilliseconds; using (var tcpClient = await TcpUtils.ConnectAsync(info.Url, ServerStore.Engine.TcpConnectionTimeout).ConfigureAwait(false)) using (var stream = await TcpUtils .WrapStreamWithSslAsync(tcpClient, info, ServerStore.Engine.ClusterCertificate, ServerStore.Engine.TcpConnectionTimeout).ConfigureAwait(false)) using (ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { var msg = new DynamicJsonValue { [nameof(TcpConnectionHeaderMessage.DatabaseName)] = null, [nameof(TcpConnectionHeaderMessage.Operation)] = TcpConnectionHeaderMessage.OperationTypes.Ping, [nameof(TcpConnectionHeaderMessage.OperationVersion)] = -1 }; using (var writer = new BlittableJsonTextWriter(context, stream)) using (var msgJson = context.ReadObject(msg, "message")) { result.SendTime = sp.ElapsedMilliseconds; context.Write(writer, msgJson); } using (var response = context.ReadForMemory(stream, "cluster-ConnectToPeer-header-response")) { JsonDeserializationServer.TcpConnectionHeaderResponse(response); result.RecieveTime = sp.ElapsedMilliseconds; } } } } catch (Exception e) { result.Error = e.ToString(); } return(result); }
private void BeetleStatic(object state) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Beetle Status\r\n"); sb.AppendFormat("\t\t\t\tReceive SAEA Pool:{0}\r\n", TcpUtils.GetAsyncEventPoolStatus()); sb.AppendFormat("\t\t\t\tReceive Buffer Pool:{0}\r\n", TcpUtils.GetReceiveBufferStatus()); sb.AppendFormat("\t\t\t\tSend Buffer Pool:{0}\r\n", TcpUtils.GetSendBufferStatus()); sb.AppendFormat("\t\t\t\tReceive Bytes :{0}\r\n", TcpUtils.ReceiveBytes); sb.AppendFormat("\t\t\t\tSend Bytes :{0}\r\n", TcpUtils.SendBytes); sb.AppendFormat("\t\t\t\tReceive Messages :{0}\r\n", TcpUtils.ReceiveMessages); sb.AppendFormat("\t\t\t\tSend Messages :{0}\r\n", TcpUtils.SendMessages); IList <int> receivequeue = TcpUtils.GetReceiveDespatchStatus(); IList <int> sendqueue = TcpUtils.GetSendDespatchStatus(); IList <int> workqueue = TcpUtils.GetWorkDespatchsStatus(); sb.AppendFormat("\t\t\t\tReceive Queue:"); for (int i = 0; i < receivequeue.Count; i++) { sb.AppendFormat("[D{0}:{1}]", i, receivequeue[i]); } sb.AppendFormat("\r\n"); sb.AppendFormat("\t\t\t\tSend Queue:"); for (int i = 0; i < sendqueue.Count; i++) { sb.AppendFormat("[D{0}:{1}]", i, sendqueue[i]); } sb.AppendFormat("\r\n"); sb.AppendFormat("\t\t\t\tWork Queue:"); for (int i = 0; i < workqueue.Count; i++) { sb.AppendFormat("[D{0}:{1}]", i, workqueue[i]); } sb.AppendFormat("\r\n"); foreach (ServerItem item in mServers) { if (item.Server != null) { sb.AppendFormat("\t\t\t\t{0} [listen:{1}] [Online:{2}]\r\n", item.Name, item.Server.Server.Socket.LocalEndPoint, item.Server.Server.Count); } } Utils.GetLog <ServerFactory>().Info(sb.ToString()); }
private void SendFileNodeDescription(TcpClient tcpClient, string filePath) { string fileName = Path.GetFileName(filePath); long dimension = new FileInfo(filePath).Length; // preparing file node FileNode fileNode = new FileNode { Name = fileName, Dimension = dimension, MimeType = MimeMapping.GetMimeMapping(fileName), SenderUserName = Properties.Settings.Default.Name }; string jsonFileNodeDescription = JsonConvert.SerializeObject(fileNode); TcpUtils.SendDescription(tcpClient, jsonFileNodeDescription); }
public void StartStopServer() { if (_manager.ServerConnected) { _manager.KillServer(); } else { if (_serverPort.Text.Trim().ToLower() == "any") { _serverPort.Text = TcpUtils.FreeTcpPort().ToString(); } int pars; int?port = Int32.TryParse(_serverPort.Text, out pars) ? pars : (int?)null; _manager.RunServer(_serverNameTextBox.Text, port); } }
public override async Task <RachisConnection> ConnectToPeer(string url, X509Certificate2 certificate) { TimeSpan time; using (ContextPoolForReadOnlyOperations.AllocateOperationContext(out TransactionOperationContext ctx)) using (ctx.OpenReadTransaction()) { time = _parent.ElectionTimeout * (_parent.GetTopology(ctx).AllNodes.Count - 2); } var tcpClient = await TcpUtils.ConnectAsync(url, time); return(new RachisConnection { Stream = tcpClient.GetStream(), SupportedFeatures = new TcpConnectionHeaderMessage.SupportedFeatures(TcpConnectionHeaderMessage.NoneBaseLine40000), Disconnect = () => tcpClient.Client.Disconnect(false) }); }
public static async Task ConnectToClientNodeAsync(RavenServer server, TcpConnectionInfo tcpConnectionInfo, TimeSpan timeout, Logger log, string database, NodeConnectionTestResult result) { TcpClient tcpClient; string url; (tcpClient, url) = await TcpUtils.ConnectSocketAsync(tcpConnectionInfo, timeout, log); var connection = await TcpUtils.WrapStreamWithSslAsync(tcpClient, tcpConnectionInfo, server.Certificate.Certificate, server.CipherSuitesPolicy, timeout); using (tcpClient) { using (server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext ctx)) await using (var writer = new AsyncBlittableJsonTextWriter(ctx, connection)) { await WriteOperationHeaderToRemote(writer, TcpConnectionHeaderMessage.OperationTypes.TestConnection, database); using (var responseJson = await ctx.ReadForMemoryAsync(connection, $"TestConnectionHandler/{url}/Read-Handshake-Response")) { var headerResponse = JsonDeserializationServer.TcpConnectionHeaderResponse(responseJson); switch (headerResponse.Status) { case TcpConnectionStatus.Ok: result.Success = true; break; case TcpConnectionStatus.AuthorizationFailed: result.Success = false; result.Error = $"Connection to {url} failed because of authorization failure: {headerResponse.Message}"; break; case TcpConnectionStatus.TcpVersionMismatch: result.Success = false; result.Error = $"Connection to {url} failed because of mismatching tcp version: {headerResponse.Message}"; await WriteOperationHeaderToRemote(writer, TcpConnectionHeaderMessage.OperationTypes.Drop, database); break; } } } } }
private void ReceiveDirectory(TcpClient client) { string jsonDirectoryNodeDescription = TcpUtils.ReceiveDescription(client); DirectoryNode directoryNode = JsonConvert.DeserializeObject <DirectoryNode>(jsonDirectoryNodeDescription); String destinationDir = null; // retrieving destination dir if (Properties.Settings.Default.AutoAccept) { TcpUtils.SendAcceptanceResponse(client); // retrieving default dir destinationDir = Properties.Settings.Default.DefaultDir; } else { // asking user for file acceptance UI.FilesAcceptance fileAcceptanceWindow = new UI.FilesAcceptance(directoryNode); // blocking call until window is closed fileAcceptanceWindow.ShowDialog(); if (fileAcceptanceWindow.AreFilesAccepted) { // file accepted TcpUtils.SendAcceptanceResponse(client); destinationDir = fileAcceptanceWindow.DestinationDir; } else { // file not accepted or window closed TcpUtils.SendRefuseResponse(client); return; } } PopulateDirectory(client, directoryNode, destinationDir); }
public void Listen() { try { TcpUtils.ReleasePort(Services.Config.Server.Port); server.Start(); Services.Store.Dispatch(new AppConnectionsChangedAction( new AppConnectionsChangedActionPayload { ServerConnected = ConnectionStatus.Connected })); Services.Messages.Info($"The server is listening on {Services.Config.Server.Ip}:{Services.Config.Server.Port}", MessageCategory.PLC); } catch (Exception e) { Services.Store.Dispatch(new AppConnectionsChangedAction( new AppConnectionsChangedActionPayload { ServerConnected = ConnectionStatus.Disconnected })); Services.Messages.Error($"Server unable to listen on '{Services.Config.Server.Ip}:{Services.Config.Server.Port}'", MessageCategory.PLC, e); } }
private async void InitListener() { var tcpServer = new TcpListener(IPAddress.Any, ServerListenerPort); tcpServer.Start(); while (true) { var client = await tcpServer.AcceptTcpClientAsync(); var clientIp = ((IPEndPoint)client.Client.RemoteEndPoint).Address; tcpClient = new TcpClient(); tcpClient.Connect(new IPEndPoint(clientIp, ClientListenerPort)); Invoke(new Action( () => { lbConnectionStatus.Text = $"Подключен к {clientIp}"; btnSend.Enabled = true; })); var stream = client.GetStream(); while (true) { var message = TcpUtils.ReadMessage(stream); if (string.IsNullOrEmpty(message)) { Invoke(new Action( () => { lbConnectionStatus.Text = "Не подключен"; btnSend.Enabled = false; })); break; } message = DateTime.Now.ToString("t") + ": " + message; lbMessages.Invoke(new Action(() => lbMessages.Items.Add(message))); } } }
public async Task CreateServerWithSameUrlButDifferentPortShouldNotBeSame() { var settings1 = new FluentProxySettings { InternalPort = TcpUtils.FindFreeTcpPort(), ExternalUrl = new Uri("https://api.exmo.com"), }; var settings2 = new FluentProxySettings { InternalPort = TcpUtils.FindFreeTcpPort(), ExternalUrl = new Uri("https://api.exmo.com"), }; settings1.InternalPort.Should().NotBe(settings2.InternalPort); var fluentProxyServer1 = await FluentProxyFactory.CreateServer(settings1); var fluentProxyServer2 = await FluentProxyFactory.CreateServer(settings2); fluentProxyServer1.Should().NotBeSameAs(fluentProxyServer2); }
public override async Task <RachisConnection> ConnectToPeer(string url, string tag, X509Certificate2 certificate, CancellationToken token) { TimeSpan time; using (ContextPoolForReadOnlyOperations.AllocateOperationContext(out ClusterOperationContext ctx)) using (ctx.OpenReadTransaction()) { time = _parent.ElectionTimeout * (_parent.GetTopology(ctx).AllNodes.Count - 2); } var tcpClient = await TcpUtils.ConnectAsync(url, time, token : token); try { var stream = tcpClient.GetStream(); var conn = new RachisConnection { Stream = stream, SupportedFeatures = TcpConnectionHeaderMessage.GetSupportedFeaturesFor( TcpConnectionHeaderMessage.OperationTypes.Cluster, TcpConnectionHeaderMessage.ClusterWithMultiTree), Disconnect = () => { using (tcpClient) { tcpClient.Client.Disconnect(false); } } }; return(conn); } catch { using (tcpClient) { tcpClient.Client.Disconnect(false); } throw; } }
private void btnSend_Click(object sender, EventArgs e) { var message = tbMessage.Text; if (string.IsNullOrEmpty(message)) { MessageBox.Show(this, "Сообщение не может быть пустым.", "Некорректные параметры", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (!TcpUtils.SendMessage(message, tcpClient.GetStream())) { MessageBox.Show(this, "Не удалось отправить сообщение: клиент разорвал соединение. Подключение будет закрыто", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private async void InitListener() { var tcpServer = new Sockets.TcpListener(IPAddress.Any, ClientListenerPort); tcpServer.Start(); while (true) { tcpReciever = await tcpServer.AcceptTcpClientAsync(); var stream = tcpReciever.GetStream(); properlyDisconnected = false; while (true) { var message = TcpUtils.ReadMessage(stream); if (string.IsNullOrEmpty(message)) { if (!properlyDisconnected) { Invoke(new Action(() => { MessageBox.Show(this, "Соединение с сервером потеряно. Подключение будет закрыто", "Сервер отключен", MessageBoxButtons.OK, MessageBoxIcon.Information); Disconnect(); })); } break; } message = DateTime.Now.ToString("t") + ": " + message; lbMessages.Invoke(new Action(() => lbMessages.Items.Add(message))); } } }
public void SendDirectory() { TcpClient tcpClient = new TcpClient(_server, _port); // sending directory request TcpUtils.SendDirectoryRequest(tcpClient); // sending direcroty description DirectoryNode directoryNode = SendDirectoryNodeDescription(tcpClient); // gettin response string responseCommand = TcpUtils.ReceiveCommand(tcpClient, Constants.TRANSFER_TCP_ACCEPT.Length); if (!responseCommand.Equals(Constants.TRANSFER_TCP_ACCEPT)) { ManageRefusedDirectory(_path); return; } // sending directory content SendDirectoryContent(directoryNode, _path); tcpClient.Close(); }