protected override void OnStart(string[] args) { try { Task.Factory.StartNew(() => { try { _tcpServiceHost = new TcpServerHelper2(IPAddress.Parse(CommandLineArgs.BindIpAddress)); Program.MainLogSystem.WriteLogEntry("Binded to " + _tcpServiceHost.ListenAddress); _tcpServiceHost.OnLogMessage += (client, message) => { if (client != null && client.ClientSocket != null && client.ClientSocket.Connected) message = "Log from: " + client.ClientSocket.Client.RemoteEndPoint.ToString() + " " + message; Program.MainLogSystem.WriteLogEntry(message); }; _tcpServiceHost.Online(); _udpService = new UdpHelper(); _udpService.OnReceiveData += (endPoint, data) => { try { Packet packet = new Packet(data); if (packet.Opcode == Opcodes.ServerSearch) { string addr = _tcpServiceHost.ListenAddress.ToString(); _udpService.SendPacket(endPoint.Address, new Packet(Guid.Empty, Opcodes.ServerFound, addr)); Program.MainLogSystem.WriteLogEntry("Broadcast query accepted from " + endPoint.Address); } } catch (Exception ex) { Program.MainLogSystem.WriteLogEntry("UdpHelper OnReceiveData exception: " + ex.Message); throw; } }; _udpService.Start(); } catch (Exception ex) { Program.MainLogSystem.WriteLogEntry("OnStart exception: "+ex.Message); throw; } }, TaskCreationOptions.LongRunning).ContinueWith(task => { if (task.IsFaulted) { if (task.Exception != null) throw task.Exception; } }, TaskContinuationOptions.OnlyOnFaulted); } catch { throw; } }
public void SendData(Packet packet) { var trData = Encoding.ASCII.GetBytes(packet.Pack() + Packet.EndOfPacket); var stream = _client.GetStream(); stream.Write(trData, 0, trData.Length); stream.Flush(); }
public void SendPacket(IPAddress address, Packet packet) { UdpClient client = new UdpClient(); IPEndPoint ip = new IPEndPoint(address, IpDefaultPorts.DefaultUdpResponsePort); byte[] bytes = Encoding.ASCII.GetBytes(packet.Pack()); client.Send(bytes, bytes.Length, ip); client.Close(); }
public void HandleCommunication() { ClientRemoteId = _clientSocket.Client.RemoteEndPoint.ToString(); while (_isRunning) { try { byte[] bytesBuffer = new byte[4096]; string dataBuffer = string.Empty; NetworkStream networkStream = _clientSocket.GetStream(); int bytesRead = 0; while ((bytesRead = networkStream.Read(bytesBuffer, 0, bytesBuffer.Length)) > 0) { dataBuffer += Encoding.ASCII.GetString(bytesBuffer, 0, bytesRead); if (dataBuffer.IndexOf(Packet.EndOfPacket, System.StringComparison.Ordinal) >= 0 || dataBuffer.Length > 4096) { break; } } Packet inputPacket=new Packet(Encoding.ASCII.GetString(bytesBuffer)); if (inputPacket.Opcode == Opcodes.Invalid) { throw new Exception("[" + Thread.CurrentThread.ManagedThreadId + "] Invalid opcode received. Terminate client thread " + ClientRemoteId); } if (inputPacket.Opcode == Opcodes.Accepted) { bool tested = false; lock (_listLock) { if (_sendedSequinces.Contains(inputPacket.Sequence)) { _sendedSequinces.Remove(inputPacket.Sequence); tested = true; } } if (!tested) { OnDeadCommunicator(this, new Exception("Packet with invalid sequince received!")); } } else { OnPacketReceive(this, inputPacket); SendData(new Packet(inputPacket.Sequence, Opcodes.Accepted, string.Empty)); } Thread.Sleep(5); } catch (Exception ex) { if (ex is InvalidOperationException) return; OnDeadCommunicator(this, ex); } } }
public void Run() { Task.Factory.StartNew(() => { int bytesRead = 0; NetworkStream stream = _client.GetStream(); byte[] messageBuffer = new byte[4096]; string inpData = string.Empty; while ((bytesRead = stream.Read(messageBuffer, 0, messageBuffer.Length)) > 0) { inpData += Encoding.ASCII.GetString(messageBuffer, 0, bytesRead); if (inpData.IndexOf(Environment.NewLine + Environment.NewLine, System.StringComparison.Ordinal) >= 0 || inpData.Length > 4096) { break; } } Packet inputPacket=new Packet(); }).ContinueWith(task => { }, TaskContinuationOptions.OnlyOnFaulted); }
public void ConnectService() { MiniSplash_TF splash = new MiniSplash_TF(Resources.load1) { Text = @"Запуск приложения", StatusText = @"Поиск сервера уведомлений" }; UdpHelper udpService = new UdpHelper(IpDefaultPorts.DefaultUdpResponsePort); udpService.OnReceiveData += (endPoint, data) => { Packet packet = new Packet(data); if (packet.Opcode == Opcodes.ServerFound) { _serverAddress = packet.Data; } }; splash.WorkingFunction = () => { try { List<string> broadcasts = new List<string>(); foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties properties = netif.GetIPProperties(); foreach (UnicastIPAddressInformation unicast in properties.UnicastAddresses) { if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) continue; if (unicast.IPv4Mask == null) continue; byte[] ipAdressBytes = unicast.Address.GetAddressBytes(); byte[] subnetMaskBytes = unicast.IPv4Mask.GetAddressBytes(); byte[] broadcastAddress = new byte[ipAdressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); } broadcasts.Add(string.Join(".", broadcastAddress)); } } _serverAddress = string.Empty; udpService.Start(); bool finished = false; int trying = 1; while (!finished && trying <= 5) { splash.StatusText = @"Поиск сервера уведомлений, попытка: " + trying; broadcasts.ForEach(ba => { UdpClient client = new UdpClient(); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ba), IpDefaultPorts.DefaultUdpListenPort); byte[] bytes = Encoding.ASCII.GetBytes(new Packet(Guid.Empty, Opcodes.ServerSearch, string.Empty).Pack()); client.Send(bytes, bytes.Length, ip); client.Close(); Thread.Sleep(200); }); if (_serverAddress != string.Empty) finished = true; trying++; } } catch (Exception ex) { OnMessageShow(ex.Message); throw; } }; splash.ShowDialog(); #if DEBUG _serverAddress = "10.100.1.47"; #endif if (_serverAddress != string.Empty) { Reconnect(_serverAddress); } else { OnMessageShow("Сервис уведомлений не найден, пытаемся соедениться напрямую!"); Reconnect("10.100.1.21"); } udpService.Stop(); }
//private void ServerHelperInit() // { // _serverHelper = new TcpServerHelper(null,LocalServerPort); // _serverHelper.OnBeforeStop += Unsubscribe; // _serverHelper.OnReceiveData += (info, data) => // { // Packet packet = new Packet(data); // if (packet.Opcode == Opcodes.Invalid) // return; // if (packet.Opcode == Opcodes.ServerShutdown) // { // _serverHelper.Offline(); // MessageBox.Show("server going offline"); // return; // } // if (packet.Opcode == Opcodes.NotifyAll) // { // NotifyData nData = new NotifyData(packet.Data); // MessageBox.Show(nData.Data); // return; // } // }; // _serverHelper.Online(); // } private void button1_Click(object sender, EventArgs e) { MiniSplash_TF splash = new MiniSplash_TF(Resources.load4) { Text = @"Запуск приложения", StatusText = @"Поиск сервера уведомлений" }; UdpHelper udpService = new UdpHelper(IpDefaultPorts.DefaultUdpResponsePort); udpService.OnReceiveData += (endPoint, data) => { Packet packet = new Packet(data); if (packet.Opcode == Opcodes.ServerFound) { _serverAddress = packet.Data; } }; splash.WorkingFunction = () => { try { List<string> broadcasts = new List<string>(); foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties properties = netif.GetIPProperties(); foreach (UnicastIPAddressInformation unicast in properties.UnicastAddresses) { if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) continue; if (unicast.IPv4Mask == null) continue; byte[] ipAdressBytes = unicast.Address.GetAddressBytes(); byte[] subnetMaskBytes = unicast.IPv4Mask.GetAddressBytes(); byte[] broadcastAddress = new byte[ipAdressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); } broadcasts.Add(string.Join(".", broadcastAddress)); } } _serverAddress = string.Empty; udpService.Start(); bool finished = false; int trying = 1; while (!finished && trying <= 5) { splash.StatusText = @"Поиск сервера уведомлений, попытка: " + trying; broadcasts.ForEach(ba => { UdpClient client = new UdpClient(); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ba), IpDefaultPorts.DefaultUdpListenPort); byte[] bytes = Encoding.ASCII.GetBytes(new Packet(Guid.Empty, Opcodes.ServerSearch, string.Empty).Pack()); client.Send(bytes, bytes.Length, ip); client.Close(); Thread.Sleep(200); }); if (_serverAddress != string.Empty) finished = true; trying++; } } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } }; splash.ShowDialog(this); if (_serverAddress != string.Empty) { if (_clientHelper.Client.Connected) { _clientHelper.SendData(new Packet(Guid.NewGuid(), Opcodes.Unsubscribe, Appid.ToString())); _clientHelper.Stop(); } if (_clientHelper.Connect(_serverAddress, IpDefaultPorts.DefaultTcpServerListenerPort)) { _clientHelper.Start(); } else { MessageBox.Show("not connect to " + _serverAddress); } } else { MessageBox.Show("service not found"); } udpService.Stop(); }
public void ParsePacket(ClientCommunicator client, Packet packet) { if (packet.Opcode == Opcodes.Invalid) return; OnLogMessage(client, "[" + Thread.CurrentThread.ManagedThreadId + "] Received opcode:" + Enum.GetName(typeof(Opcodes), packet.Opcode)); switch (packet.Opcode) { case Opcodes.NotifyAll: { NotifyData inputNotifyData = new NotifyData(packet.Data); NotifyData outputNotifyData = new NotifyData(Guid.Empty, inputNotifyData.Data, false); Packet outputpacket = new Packet(Guid.NewGuid(), Opcodes.NotifyAll, outputNotifyData.Pack()); foreach (ClientCommunicator communicator in _clients) { if (client.Equals(communicator)) { if (inputNotifyData.NotifySelf) communicator.SendData(outputpacket); } else { communicator.SendData(outputpacket); } } break; } case Opcodes.NotifyApp: { NotifyData inputNotifyData = new NotifyData(packet.Data); var subs = GetAppSubscribers(inputNotifyData.AppId); IEnumerable<ClientCommunicator> clientCommunicators = subs as IList<ClientCommunicator> ?? subs.ToList(); if (clientCommunicators.Any()) { NotifyData outputNotifyData = new NotifyData(inputNotifyData.AppId, inputNotifyData.Data, false); Packet outputpacket = new Packet(Guid.NewGuid(), Opcodes.NotifyApp, outputNotifyData.Pack()); foreach (ClientCommunicator communicator in clientCommunicators) { if (client.Equals(communicator)) { if (inputNotifyData.NotifySelf) communicator.SendData(outputpacket); } else { communicator.SendData(outputpacket); } } } break; } case Opcodes.Subscribe: { Guid appId; if (Guid.TryParse(packet.Data, out appId)) { var subs = GetAppSubscribers(appId); var sub = subs.SingleOrDefault(s => s.Equals(client)); if (sub == null) { client.ApplicationId = appId; OnLogMessage(client, "[" + Thread.CurrentThread.ManagedThreadId + "] subscribe to " + appId); } else { OnLogMessage(client, "[" + Thread.CurrentThread.ManagedThreadId + "] already subscribed"); } } break; } case Opcodes.Unsubscribe: { Guid appId; if (Guid.TryParse(packet.Data, out appId)) { var subs = GetAppSubscribers(appId); var sub = subs.SingleOrDefault(s => s.Equals(client)); if (sub != null) { sub.ApplicationId = Guid.Empty; OnLogMessage(client, "[" + Thread.CurrentThread.ManagedThreadId + "] unsubscribe from " + appId); } else { OnLogMessage(client, "[" + Thread.CurrentThread.ManagedThreadId + "] not subscribed"); } } break; } default: OnLogMessage(client, "[" + Thread.CurrentThread.ManagedThreadId + "] Unknown opcode " + packet.Opcode.ToString()); break; } }
public void SendData(Packet packet) { try { lock (_listLock) { _sendedSequinces.Add(packet.Sequence); } var packetData = Encoding.ASCII.GetBytes(packet.Pack() + Packet.EndOfPacket); if (_client.Client!=null && _client.Connected) { var stream = _client.GetStream(); stream.Write(packetData, 0, packetData.Length); stream.Flush(); } else { OnClientError("Попытка передачи уведомления не удалась!"); } } catch (Exception) { OnClientError("Попытка передачи уведомления не удалась!"); ; } }
private void ReceiveCommunication() { try { while (_isRunning) { try { byte[] bytesBuffer = new byte[4096]; string dataBuffer = string.Empty; NetworkStream networkStream = _client.GetStream(); int bytesRead = 0; while ((bytesRead = networkStream.Read(bytesBuffer, 0, bytesBuffer.Length)) > 0) { dataBuffer += Encoding.ASCII.GetString(bytesBuffer, 0, bytesRead); if (dataBuffer.IndexOf(Packet.EndOfPacket, System.StringComparison.Ordinal) >= 0 || dataBuffer.Length > 4096) { break; } } Packet inputPacket = new Packet(Encoding.ASCII.GetString(bytesBuffer)); if (inputPacket.Opcode == Opcodes.Invalid) { continue; } //if (inputPacket.Opcode == Opcodes.ServerShutdown) //{ // Stop(); // OnClientError("Server going offline"); // return; //} if (inputPacket.Opcode == Opcodes.Accepted) { lock (_listLock) { if (_sendedSequinces.Contains(inputPacket.Sequence)) { _sendedSequinces.Remove(inputPacket.Sequence); } else { throw new Exception("Packet with invalid sequince received!"); } } } else { OnPacketReceive(inputPacket); if (inputPacket.Opcode != Opcodes.ServerShutdown) SendData(new Packet(inputPacket.Sequence, Opcodes.Accepted, string.Empty)); } } catch (ThreadInterruptedException) { break; } catch (Exception ex) { if (ex is IOException || ex is SocketException) { if (!ex.Message.Contains("WSACancelBlockingCall")) throw; } else throw; } } } catch (Exception ex) { if (ex is IOException || ex is SocketException) { if (!ex.Message.Contains("WSACancelBlockingCall")) OnClientError("Нет соединения с сервисом уведомлений!"); } else OnClientError("Нет соединения с сервисом уведомлений!"); } }
public void SendData(Packet packet) { try { lock (_listLock) { _sendedSequinces.Add(packet.Sequence); } var packetData = Encoding.ASCII.GetBytes(packet.Pack() + Packet.EndOfPacket); var stream = _clientSocket.GetStream(); stream.Write(packetData, 0, packetData.Length); stream.Flush(); } catch (Exception ex) { OnDeadCommunicator(this, ex); ; } }