public void SReader() { while (true) { if (kolejkaS.Count == 0) { Thread.Sleep(100); continue; } try { SPacket pakiet; if(!kolejkaS.TryDequeue(out pakiet)) { Thread.Sleep(100); continue;//jeśli nie udało się zdejmowanie przejdź do następnego obiegu po chwili pauzy } String komenda = pakiet.getParames().ElementAt(0);//zczytywanie komendy String nowakomenda = ""; if (komenda.Equals("IS_LINK_AVAILABLE"))//to jest do do wysyłania pakietu próbnego do sąsiada o zadanym adresie np. IS_ALIVE 1.2.3 dawne IS_ALIVE { int i2 = -1; if (pakiet.getParames().Count > 1) i2 = int.Parse(pakiet.getParames().ElementAt(2)); Address sprawdzany = Address.Parse(pakiet.getParames().ElementAt(1)); Tuple<Address, int> argus = new Tuple<Address, int>(sprawdzany, i2); CzyZyjeRun(argus);//odpowiedzią zajmuje się metoda CzyZyje continue; } /*else if (komenda.Equals("IS_LINK_AVAILABLE")) { Address sprawdzany = Address.Parse(pakiet.getParames().ElementAt(1)); for(int i=0; i<parent.routeList.Count;i++) { if(sprawdzany.Equals(parent.routeList.ElementAt(i).destAddr))//szukamy na routelist zadanego adresu { if(parent.routeList.ElementAt(i).bandwidth>=2)//gdy przepustowość co najmniej 2 to ok { nowakomenda = "YES_AVAILABLE " + sprawdzany.ToString(); break; } else { nowakomenda = "NO_AVAILABLE " + sprawdzany.ToString(); break; } } } }*/ else if(komenda.Equals("ADD_MAPPING")) { if(pakiet.getParames().Count==7) { List<String> p = pakiet.getParames(); int vp1, vc1, vp2, vc2; Address a1, a2; a1 = Address.Parse(p.ElementAt(1)); vp1 = int.Parse(p.ElementAt(2)); vc1 = int.Parse(p.ElementAt(3)); a2 = Address.Parse(p.ElementAt(4)); vp2 = int.Parse(p.ElementAt(5)); vc2 = int.Parse(p.ElementAt(6)); int p1 = AddressToPort(a1); int p2 = AddressToPort(a2); parent.addSingleEntry(p1, vp1, vc1, p2, vp2, vc2); ZajmijZasob(a1, a2); nowakomenda = "MSG zadanie ADD wykonane"; } else { nowakomenda = "ERROR ZŁA LICZBA PARAMETRÓW W ADD"; } } else if(komenda.Equals("DEL_MAPPING")) { if (pakiet.getParames().Count == 7) { List<String> p = pakiet.getParames(); int vp1, vc1, vp2, vc2; Address a1, a2; a1 = Address.Parse(p.ElementAt(1)); vp1 = int.Parse(p.ElementAt(2)); vc1 = int.Parse(p.ElementAt(3)); a2 = Address.Parse(p.ElementAt(4)); vp2 = int.Parse(p.ElementAt(5)); vc2 = int.Parse(p.ElementAt(6)); int p1 = AddressToPort(a1); parent.removeSingleEntry(p1, vp1, vc1); ZwolnijZasob(a1, a2); nowakomenda = "MSG zadanie DELETE wykonane"; } else { nowakomenda = "ERROR ZŁA LICZBA PARAMETRÓW W DELETE"; } } else if (komenda.Equals("REQ_TOPOLOGY")) { nowakomenda = "TOPOLOGY"; for(int i=0;i<parent.routeList.Count;i++) { nowakomenda += " " + parent.routeList.ElementAt(i).destAddr.ToString(); } } else if(komenda.Equals("DEAD")) { bool czySonsiad = false; Address sprawdzany = Address.Parse(pakiet.getParames().ElementAt(1)); for (int i = 0; i < parent.routeList.Count; i++ ) { if(sprawdzany.Equals(parent.routeList.ElementAt(i).destAddr)) { czySonsiad = true; break; } } if(czySonsiad) { SPacket wysylanyCC, wysylanyRC; wysylanyCC = new SPacket(adresLRM, adresCC, "DEAD " + sprawdzany.ToString()); wysylanyRC = new SPacket(adresLRM, adresRC, "DEAD " + sprawdzany.ToString()); wyslijSPacket(wysylanyCC); wyslijSPacket(wysylanyRC); } else { //do nothing? } continue;//nie swapujemy pakietu, bo to nie odpowiedź } else if(komenda.Equals("REQ_VPATHS")) { List<String> lista = new List<string>(); lista.Add("RES_VPATHS"); for(int i=0; i<parent.routeList.Count;i++) { String result = parent.routeList.ElementAt(i).destAddr.ToString(); for (int j = 0; j < parent.routeList.ElementAt(i).VPIList.Count; j++) { result += "#" + parent.routeList.ElementAt(i).VPIList.ElementAt(j).ToString(); } lista.Add(result); } SPacket pkt = new SPacket(adresLRM, adresCC, lista); wyslijSPacket(pkt); continue; } pakiet.Swap(nowakomenda);//metoda zamienia src i dest i ustawia nowe parames wyslijSPacket(pakiet); } catch (Exception e) { Console.Out.WriteLine(e.Message); } } }
private void reqTopButton_Click(object sender, EventArgs e) { foreach (string addr in networkGraph.Vertices) { Address address; if(Address.TryParse(addr,out address)){ SPacket pck = new SPacket(myAddr.ToString(), address.ToString(), "REQ_TOPOLOGY"); whatToSendQueue.Enqueue(pck); } } }
/// <summary> /// wysłanie topologii do innych RC /// </summary> private void sendTopology() { /* List<String> subnets = new List<String>(); List<int> subnetsNumbers = new List<int>(); subnets = availableSubnetworks.Values.SelectMany(x => x).ToList(); foreach (String str in subnets) { String[] _str = str.Split('.'); int _subnetNumber = int.Parse(_str[1]); if (!subnetsNumbers.Contains(_subnetNumber)) subnetsNumbers.Add(_subnetNumber); } foreach (int subnetNumber in subnetsNumbers) { List<String> paramsList = subnetsNumbers.ConvertAll<string>(x => x.ToString()); paramsList.Insert(0, "TOPOLOGY"); SPacket _pck = new SPacket(myAddr.ToString(), new Address(myAddr.network, subnetNumber, 0).ToString(), paramsList); whatToSendQueue.Enqueue(_pck); } */ List<String> msg = new List<String>(); msg.Add("TOPOLOGY"); foreach (int subnet in availableSubnetworksViaMe) { msg.Add(subnet.ToString()); } msg.Add("VIA"); msg.Add(string.Empty + myAddr.subnet); foreach (int subnetNumber in availableSubnetworksViaMe) { SPacket _pck = new SPacket(myAddr.ToString(), new Address(myAddr.network, subnetNumber, 0).ToString(), msg); whatToSendQueue.Enqueue(_pck); } }
private void calculatePath(IVertexAndEdgeListGraph<string, Edge<string>> graph, string root, string target, int index) { if (root != target) { if (_nodesInPath.Count != index + 1) { while (_nodesInPath.Count != index + 1) { _nodesInPath.Add(new List<string>()); } } _nodesInPath[index] = new List<string>(); //IVertexAndEdgeListGraph<string, Edge<string>> graph = networkGraph; Func<Edge<String>, double> edgeCost = e => 1; // constant cost Address targ = Address.Parse(target); if (targ.subnet != myAddr.subnet) target = targ.network + "." + targ.subnet + ".*"; //string root = _CCmsg[1]; TryFunc<string, System.Collections.Generic.IEnumerable<QuickGraph.Edge<string>>> tryGetPaths = graph.ShortestPathsDijkstra(edgeCost, root); //string target = _CCmsg[2]; IEnumerable<Edge<string>> path; if (tryGetPaths(target, out path)) { lock (_nodesInPath) { SetText("Wyznaczona trasa od " + root + " do " + target + ":"); if (nodesInPath.Count != index + 1) { while (nodesInPath.Count != index + 1) { nodesInPath.Add(new List<string>()); } } nodesInPath[index] = new List<string>(); nodesInPath[index].Add(path.First().Source); foreach (Edge<string> edge in path) { Address src; if (Address.TryParse(edge.Source, out src)) { Address tempdest; if (!Address.TryParse(edge.Target, out tempdest)) { String[] srcArr = edge.Source.Split('.'); String[] destArr = edge.Target.Split('.'); if (destArr[1] != srcArr[1] && int.Parse(srcArr[1]) == myAddr.subnet) { foreach (KeyValuePair<Address, Address> kvp in subnetConnections) { if (kvp.Key.ToString() == src.ToString()) { nodesInPath[index].Add(kvp.Value.ToString()); } } } } } SetText(edge.ToString()); nodesInPath[index].Add(edge.Target); String[] _arr = edge.Target.Split('.'); if (_arr[2] != "*") _nodesInPath[index].Add(edge.Target); } } //pyta każdego LRM o to, czy jest wolne łącze do LRM następnego w kolejce //nie pyta się ostatniego LRM w ścieżce, zakładam że jak w jedną stronę jest połączenie to i w drugą jest for (int i = 0; i < nodesInPath[index].Count - 1; i++) { string[] srcArr = nodesInPath[index][i].Split('.'); if (int.Parse(srcArr[1]) == myAddr.subnet) { List<String> _msg = new List<String>(); _msg.Add("IS_LINK_AVAILABLE"); _msg.Add(nodesInPath[index][i + 1]); _msg.Add(String.Empty + index); SPacket _pck = new SPacket(myAddr.ToString(), nodesInPath[index][i], _msg); whatToSendQueue.Enqueue(_pck); } } } else { //gdy nie ma ścieżki string ccAddr = myAddr.network + "." + myAddr.subnet + ".1"; string _routeMsg = "NO_ROUTE"; SPacket packet = new SPacket(myAddr.ToString(), ccAddr, _routeMsg); whatToSendQueue.Enqueue(packet); } } else { List<string> _msg = new List<string>(); _msg.Add("ROUTE"); _msg.Add(root); SPacket pck = new SPacket(myAddr.ToString(), myAddr.network + "." + myAddr.subnet + ".1", _msg); whatToSendQueue.Enqueue(pck); } }
/// <summary> /// metoda wywołana po wciśnięciu "połącz z chmurą" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void conToCloudButton_Click(object sender, EventArgs e) { if (!isConnectedToCloud) { if (setAddress()) { if (IPAddress.TryParse(cloudIPTextBox.Text, out cloudAddress)) { SetText("IP ustawiono jako " + cloudAddress.ToString()); } else { SetText("Błąd podczas ustawiania IP chmury (zły format?)"); } if (Int32.TryParse(cloudPortTextBox.Text, out cloudPort)) { SetText("Port chmury ustawiony jako " + cloudPort.ToString()); } else { SetText("Błąd podczas ustawiania portu chmury (zły format?)"); } cloudSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); cloudEndPoint = new IPEndPoint(cloudAddress, cloudPort); try { cloudSocket.Connect(cloudEndPoint); isConnectedToCloud = true; networkStream = new NetworkStream(cloudSocket); //writer = new StreamWriter(networkStream); //reader = new StreamReader(networkStream); List<String> _welcArr = new List<String>(); _welcArr.Add("HELLO"); SPacket welcomePacket = new SPacket(myAddr.ToString(), new Address(0 ,0, 0).ToString() , _welcArr); whatToSendQueue.Enqueue(welcomePacket); //whatToSendQueue.Enqueue("HELLO " + myAddr); receiveThread = new Thread(this.receiver); receiveThread.IsBackground = true; receiveThread.Start(); sendThread = new Thread(this.sender); sendThread.IsBackground = true; sendThread.Start(); conToCloudButton.Text = "Rozłącz"; SetText("Połączono!"); exceptionCount = 0; } catch (SocketException) { isConnectedToCloud = false; SetText("Błąd podczas łączenia się z chmurą"); SetText("Złe IP lub port? Chmura nie działa?"); } } else { SetText("Wprowadź numery sieci i podsieci"); } } else { isConnectedToCloud = false; conToCloudButton.Text = "Połącz"; SetText("Rozłączono!"); if (cloudSocket != null) cloudSocket.Close(); } }
public void sendToNextSubnet() { //DUPA while (awaitingConnections.Count() != 0) { ConnectionRequest temp = awaitingConnections[awaitingConnections.Count() - 1]; if (temp.outNodeAddr != "-" && temp.inNodeAddr != "-" && temp.destAddr != "-" && temp.nextCCAddr != "-") { //pck = new SPacket(myAddr.ToString(), myRCAddr.ToString(), "REQ_ROUTE " + temp.srcAddr + " " + temp.destAddr); //whatToSendQueue.Enqueue(pck); //awaitingConnections.Remove(temp); string msg = "REQ_CONN " + temp.connId + " " + temp.outNodeAddr + " " + temp.inNodeAddr + " " + temp.outVP + " " + temp.outVC + " " + temp.destAddr; SPacket pck = new SPacket(myAddr.ToString(), temp.nextCCAddr, msg); whatToSendQueue.Enqueue(pck); awaitingConnections.Remove(temp); } } /*string msg = "REQ_CONN " + currConnection.connId + " " + currConnection.outNodeAddr + " " + currConnection.inNodeAddr + " " + currConnection.outVP + " " + currConnection.outVC + " " + currConnection.destAddr; SPacket pck = new SPacket(myAddr.ToString(), currConnection.nextCCAddr, msg); whatToSendQueue.Enqueue(pck);*/ }
/// <summary> /// wątek odbierający wiadomości z chmury /// </summary> public void receiver() { while (isConnectedToCloud) { BinaryFormatter bf = new BinaryFormatter(); try { SPacket receivedPacket = (Packet.SPacket)bf.Deserialize(networkStream); //_msg = reader.ReadLine(); if (isDebug) SetText("Odczytano:\n" + receivedPacket.ToString()); List<String> _msgList = receivedPacket.getParames(); Address _senderAddr; if (Address.TryParse(receivedPacket.getSrc(), out _senderAddr)) { if (_senderAddr.host == 0) { #region FROM ANOTHER RC if (_msgList[0] == "TOPOLOGY") { try { _msgList.RemoveAt(0); String[] _RCmsg = _msgList.ToArray(); int realSenderSubnet = int.Parse(_RCmsg[_RCmsg.Length - 1]); int srcSubnetNumber = int.Parse(_RCmsg[_RCmsg.Length - 1]); //ostatnia część wiadomości to numer podsieci-źródła wiadomości int[] subn = new int[_RCmsg.Length - 2]; for (int i = 0; i < _RCmsg.Length - 2; i++) { //tutaj -2 by ominąć elementy "VIA" i numer podsieci-źródła wiadomości subn[i] = int.Parse(_RCmsg[i]); } foreach (int subnet in subn) { string _originSubnetAddr = _senderAddr.network + "." + realSenderSubnet + ".*"; string _subnetAddr = myAddr.network + "." + subnet + ".*"; if (subnet == myAddr.subnet) { //gdy przyszlo od podsieci bezposrednio z nami polaczonej foreach (Address myHost in availableSubnetworks.Keys) { List<string> temp; availableSubnetworks.TryGetValue(myHost, out temp); foreach (string addr in temp) { if (addr == _senderAddr.network + "." + _senderAddr.subnet + ".*") { if (!networkGraph.ContainsEdge(_originSubnetAddr, myHost.ToString())) { networkGraph.AddEdge(new Edge<string>(_originSubnetAddr, myHost.ToString())); } } } } } else { if (!networkGraph.ContainsVertex(_subnetAddr)) { //gdy mamy już taki wezel grafu - nie rób nic networkGraph.AddVertex(_subnetAddr); SetText("Dodaję nowo odkrytą sieć " + _subnetAddr); } if (!networkGraph.ContainsEdge(_originSubnetAddr, _subnetAddr)) { //gdy jest już taka krawędź - nic nie rób networkGraph.AddEdge(new Edge<string>(_originSubnetAddr, _subnetAddr)); SetText("Dodaję ścieżkę z " + _originSubnetAddr + " do " + _subnetAddr); } } if (!blockSending) sendTopology(); foreach (int _subne in availableSubnetworksViaMe) { List<string> paramList = receivedPacket.getParames(); if (paramList[0] != "TOPOLOGY") { paramList.Insert(0, "TOPOLOGY"); } Address destAddr = new Address(myAddr.network , _subne , 0); SPacket pck = new SPacket(myAddr.ToString(), destAddr.ToString(), paramList); if (!blockSending) whatToSendQueue.Enqueue(pck); } fillGraph(); ChangeButton(false); } } catch (Exception e) { //SetText("Wyjątek przy ustalaniu topologii sieci, do poprawy :<\n" + e.Message); } } #endregion } else if (_senderAddr.host == 1) { #region FROM CC //_msgList.RemoveAt(0); String[] _CCmsg = _msgList.ToArray(); if (_CCmsg[0] == "REQ_ROUTE") { IVertexAndEdgeListGraph<string, Edge<string>> graph = networkGraph; string root = _CCmsg[1]; string target = _CCmsg[2]; if (_CCmsg.Length == 4) { AdjacencyGraph<String, Edge<String>> _graph = copyGraph(networkGraph); _graph.RemoveVertex(_CCmsg[3]); graph = _graph; } numberOfRoutes++; sendRoute[numberOfRoutes] = true; calculatePath(graph, root, target, numberOfRoutes); } #endregion } else { #region FROM LRM //_msgList.RemoveAt(0); String[] _LRMmsg = _msgList.ToArray(); //gdy logowanie się LRM if (_LRMmsg[0] == "HELLO") { Address _addr; if (Address.TryParse(_LRMmsg[1], out _addr)) { if (networkGraph.ContainsVertex(_addr.ToString())) { List<String> _params = new List<String>(); _params.Add("ADDR_TAKEN"); SPacket packet = new SPacket(myAddr.ToString(), _senderAddr.ToString(), _params); whatToSendQueue.Enqueue(packet); } else { networkGraph.AddVertex(_addr.ToString()); if (isDebug) SetText("Dodano węzeł grafu"); fillGraph(); //List<String> _params = new List<String>(); //_params.Add("REQ_TOPOLOGY"); //SPacket packet = new SPacket(myAddr.ToString(), _senderAddr.ToString(), _params); //whatToSendQueue.Enqueue(packet); } } } if (_LRMmsg[0] == "DEAD") { Address deadAddr; if (Address.TryParse(_LRMmsg[1], out deadAddr)) { if (networkGraph.ContainsVertex(deadAddr.ToString())) { networkGraph.RemoveVertex(deadAddr.ToString()); fillGraph(); SetText("Węzeł o adresie " + deadAddr.ToString() + " przestał działać, usuwam go z grafu"); } } } if (_LRMmsg[0] == "TOPOLOGY") { String[] _neighbors = new String[_LRMmsg.Length - 1]; for (int i = 1; i < _LRMmsg.Length; i++) { _neighbors[i - 1] = _LRMmsg[i]; } foreach (String str in _neighbors) { Address _destAddr; Edge<string> x; //tylko temporary if (Address.TryParse(str, out _destAddr)) { string destAddr; //gdy przyszło info o wezle z innej podsieci if (_destAddr.subnet != myAddr.subnet) { subnetConnections.Add(new KeyValuePair<Address,Address>(_senderAddr, _destAddr)); //dodaje informację o tym że ta sieć jest osiągalna przeze mnie if (!availableSubnetworksViaMe.Contains(_destAddr.subnet)) { availableSubnetworksViaMe.Add(_destAddr.subnet); } destAddr = _destAddr.network + "." + _destAddr.subnet + ".*"; List<String> temp = new List<string>(); if (availableSubnetworks.ContainsKey(_senderAddr)) { if (availableSubnetworks.TryGetValue(_senderAddr, out temp)) { availableSubnetworks.Remove(_senderAddr); } } temp.Add(destAddr); availableSubnetworks.Add(_senderAddr, temp); } else destAddr = _destAddr.ToString(); //jeśli jest już taka ścieżka nic nie rób if (networkGraph.TryGetEdge(_senderAddr.ToString(), destAddr, out x)) { } //jeśli nie ma else { //jeśli nie ma w węzłach grafu węzła z topologii - dodaj go if (!networkGraph.Vertices.Contains(destAddr)) networkGraph.AddVertex(destAddr); //dodaj ścieżkę networkGraph.AddEdge(new Edge<String>(_senderAddr.ToString(), destAddr)); if (isDebug) SetText("Dodano ścieżkę z " + _senderAddr.ToString() + " do " + destAddr); //rysuj graf fillGraph(); } } } } //gdy przyszła wiadomość że łącze jest wolne if (_LRMmsg[0] == "YES") { lock (_nodesInPath) { int _index = int.Parse(_LRMmsg[2]); if (_nodesInPath[_index].Contains(_LRMmsg[1])) _nodesInPath[_index].Remove(_LRMmsg[1]); string[] _msgArr = _LRMmsg[1].Split('.'); string temp = _msgArr[0] + "." + _msgArr[1] + ".*"; if (_nodesInPath[_index].Contains(temp)) _nodesInPath[_index].Remove(temp); if (_nodesInPath[_index].Count == 0) { List<string> _routeMsg = new List<string>(); string ccAddr = myAddr.network + "." + myAddr.subnet + ".1"; _routeMsg.Add("ROUTE"); foreach (string str in nodesInPath[_index]) _routeMsg.Add(str); SPacket packet = new SPacket(myAddr.ToString(), ccAddr, _routeMsg); if (sendRoute[_index]) { whatToSendQueue.Enqueue(packet); sendRoute[_index] = false; } } } } //gdy brak zasobów if (_LRMmsg[0] == "NO") { lock (_nodesInPath) { int _index = int.Parse(_LRMmsg[2]); string _root = nodesInPath[_index][0]; string _target = nodesInPath[_index][nodesInPath.Count-1]; numberOfRoutes++; if (_nodesInPath.Count != numberOfRoutes + 1) { while (_nodesInPath.Count != numberOfRoutes + 1) { _nodesInPath.Add(new List<string>()); } } if (nodesInPath.Count != numberOfRoutes + 1) { while (nodesInPath.Count != numberOfRoutes + 1) { nodesInPath.Add(new List<string>()); } } _nodesInPath[numberOfRoutes] = new List<string>(); nodesInPath[numberOfRoutes] = new List<string>(); //tymczasowy graf reprezentujący sieć bez zajętego łącza AdjacencyGraph<String, Edge<String>> _networkGraph = copyGraph(networkGraph); Edge<string> edge; _networkGraph.TryGetEdge(receivedPacket.getSrc(), _LRMmsg[1], out edge); _networkGraph.RemoveEdge(edge); //_networkGraph.RemoveEdge(new Edge<String>(receivedPacket.getSrc(), _LRMmsg[1])); //_networkGraph.RemoveEdge(new Edge<String>(_LRMmsg[1], receivedPacket.getSrc())); IVertexAndEdgeListGraph<string, Edge<string>> graph = _networkGraph; fillGraph(); calculatePath(graph, _root, _target, numberOfRoutes); } } #endregion } } } catch { SetText("WUT"); if (++exceptionCount == 5) { this.Invoke((MethodInvoker)delegate() { isConnectedToCloud = false; this.sendTopologyButton.Enabled = blockSending ? true : false; conToCloudButton.Text = "Połącz"; SetText("Rozłączono!"); if (cloudSocket != null) cloudSocket.Close(); }); } } } }
private void disconnectWithClient_Click(object sender, EventArgs e) { if (agent != null) { agent.whoToDisconnect = ((String)selectedClientBox.SelectedItem); agent.sendDisconnect = true; SetText("Wysyłam żądanie zerwania połączenia z " + ((String)selectedClientBox.SelectedItem) + "\n"); } if (isConnectedToControlCloud) { if ((String)selectedClientBox.SelectedItem != null) { String clientName = (String)selectedClientBox.SelectedItem; List<int> _connidList = new List<int>(); NEWCONNIDARRAY.TryGetValue(lastCalledUser, out _connidList); foreach (int _cid in _connidList) { List<String> _msgList = new List<String>(); _msgList.Add("REQ_DISCONN"); _msgList.Add(String.Empty + _cid); SPacket disconPacket = new SPacket(myAddress.ToString(), new Address(1, 0, 2).ToString(), _msgList); whatToSendQueue.Enqueue(disconPacket); } /*List<String> _msgList = new List<String>(); _msgList.Add("REQ_DISCONN"); _msgList.Add(clientName); SPacket disconPacket = new SPacket(myAddress.ToString(), new Address(1, 0, 2).ToString(), _msgList); whatToSendQueue.Enqueue(disconPacket); sendText.Enabled = false; */ /*if (userDict.ContainsKey(clientName)) { Address _adrToDiscon; userDict.TryGetValue(clientName, out _adrToDiscon); int _callIDToDiscon; addrCallIDDict.TryGetValue(_adrToDiscon, out _callIDToDiscon); List<String> _msgList = new List<String>(); _msgList.Add("REQ_DISCONN"); _msgList.Add(String.Empty + _callIDToDiscon); SPacket disconPacket = new SPacket(myAddress.ToString(), new Address(0, 0, 2).ToString(), _msgList); whatToSendQueue.Enqueue(disconPacket); sendText.Enabled = false; }*/ } else { SetText("Nie wybrano klienta\n"); } } }
private void getOtherClients_Click(object sender, EventArgs e) { if (agent != null) agent.sendGetClients = true; if (isConnectedToControlCloud) { List<String> _msgList = new List<String>(); _msgList.Add("REQ_CLIENTS"); SPacket welcomePacket = new SPacket(myAddress.ToString(), new Address(1, 0, 2).ToString(), _msgList); whatToSendQueue.Enqueue(welcomePacket); SetText("Wysłano żądanie pobrania nazwy klientów\n"); } }
/// <summary> /// wątek odbierający wiadomości z chmury /// </summary> public void controlReceiver() { while (isConnectedToControlCloud) { BinaryFormatter bf = new BinaryFormatter(); try { SPacket receivedPacket = (Packet.SPacket)bf.Deserialize(controlNetworkStream); //_msg = reader.ReadLine(); SetText("Odczytano:\n" + receivedPacket.ToString() + "\n"); if (receivedPacket.getParames()[0] == "OK" && receivedPacket.getSrc() == "1.0.2") { isClientNameSet = true; SetText("Nazwa użytkownika została zaakceptowana przez sieć\n"); } else if (receivedPacket.getParames()[0] == "NAME_TAKEN" && receivedPacket.getSrc() == "1.0.2") { SetText("Nazwa użytkownika zajęta, wybierz inną!;"); username = null; isClientNameSet = false; } else if (receivedPacket.getParames()[0] == "CLIENTS" /*&& receivedPacket.getSrc() == "0.0.1"*/) { List<string> _temp = receivedPacket.getParames(); _temp.Remove("CLIENTS"); setOtherClients(_temp); } else if (receivedPacket.getParames()[0] == "YES" && receivedPacket.getSrc() == "1.0.2") { try { SetText("Sieć zaczęła proces zestawiania połączenia z " + receivedPacket.getParames()[1] + ". Trwa oczekiwanie na akceptację drugiej strony\n"); } catch { SetText("Sieć zaczęła proces zestawiania połączenia. Trwa oczekiwanie na akceptację drugiej strony\n"); } } else if (receivedPacket.getParames()[0] == "ACK" && receivedPacket.getSrc() == "1.0.2") { SetText("Użytkownik zaakceptował żądanie połączenia. Sieć zaczyna je zestawiać\n"); } else if (receivedPacket.getParames()[0] == "NO" && receivedPacket.getSrc() == "1.0.2") { string usrToEdit = String.Empty; foreach (string usr in userDict.Keys) { Address _adr; userDict.TryGetValue(usr, out _adr); if (_adr.network == 0 && _adr.subnet == 0 && _adr.host == 0) usrToEdit = usr; } userDict.Remove(usrToEdit); SetText("Nie masz uprawnień do wykonania takiego połączenia!\n"); userToBeCalled = null; } else if (receivedPacket.getParames()[0] == "CONN_EST") { //Address calledAddress = Address.Parse(receivedPacket.getParames()[1]); SetText("Zestawiono połączenie!\n"); int callID = int.Parse(receivedPacket.getParames()[1]); string conUsr = String.Empty; foreach (Address addr in addrCallIDDict.Keys) { int _cid; if (addrCallIDDict.TryGetValue(addr, out _cid)) { string _clientName = String.Empty; foreach (Address _addr in userDict.Values) { if (_addr == addr) { _clientName = userDict.FirstOrDefault(x => x.Value.Equals(addr)).Key; } } foreach (PortVPIVCI pvv in AddrPortVPIVCIArray.Keys) { Address _adr; if (AddrPortVPIVCIArray.TryGetValue(pvv, out _adr)) { connectionEstablished(_clientName, pvv.port, pvv.VPI, pvv.VCI); } } } } } else if (receivedPacket.getParames()[0] == "CONN_DISCONN") { SetText("Rozłączono połączenie"); /*int _disconCallID = int.Parse(receivedPacket.getParames()[1]); Address _adrToDiscon = new Address(); foreach (int _callID in addrCallIDDict.Values) { if (_callID == _disconCallID) { _adrToDiscon = addrCallIDDict.FirstOrDefault(x => x.Value.Equals(_callID)).Key; } } string _clientName = String.Empty; foreach (Address _addr in userDict.Values) { if (_addr == _adrToDiscon) { _clientName = userDict.FirstOrDefault(x => x.Value.Equals(_addr)).Key; } } List<PortVPIVCI> _valuesToBreak = new List<PortVPIVCI>(); VCArray.TryGetValue(_clientName, out _valuesToBreak); foreach (PortVPIVCI _pvv in _valuesToBreak) { connectionBroken(_pvv.port, _pvv.VPI, _pvv.VCI); } SetText("Rozłączono z klientem " + _clientName + "\n");*/ }else if (receivedPacket.getParames()[0] == "CONN_NOEST") { if (lastCalledUser != null) SetText("Nie udało się nawiązać połączenia z " + lastCalledUser + "\n"); else SetText("Nie udało się nawiązać połączenia\n"); } else if (receivedPacket.getParames()[0] == "CALLING") { string message = "Dzwoni " + receivedPacket.getParames()[1] + " i chce mieć prędkość " + receivedPacket.getParames()[2] + "\n" + "Akceptujesz?"; string caption = "RING RING"; var result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { List<String> _msg = new List<String>(); _msg.Add("ACK"); _msg.Add(receivedPacket.getParames()[1]); _msg.Add(receivedPacket.getParames()[2]); _msg.Add(receivedPacket.getParames()[3]); SPacket _pck = new SPacket(myAddress.ToString(), "1.0.2", _msg); whatToSendQueue.Enqueue(_pck); lastCalledUser = receivedPacket.getParames()[1]; } else { List<String> _msg = new List<String>(); _msg.Add("NCK"); _msg.Add(receivedPacket.getParames()[1]); _msg.Add(receivedPacket.getParames()[2]); _msg.Add(receivedPacket.getParames()[3]); SPacket _pck = new SPacket(myAddress.ToString(), "1.0.2", _msg); whatToSendQueue.Enqueue(_pck); } } else { LRM.OdczytajS(receivedPacket); } } catch { SetText("WUT"); if (++exceptionCount == 5) { this.Invoke((MethodInvoker)delegate() { isConnectedToControlCloud = false; conToCloudButton.Text = "Połącz"; SetText("Rozłączono!"); if (controlCloudSocket != null) controlCloudSocket.Close(); }); } } } }
private void connectWithClientButton_Click(object sender, EventArgs e) { if (agent != null) { if ((String)selectedClientBox.SelectedItem != null) { String clientName = (String)selectedClientBox.SelectedItem; agent.whoIsCalled = clientName; agent.sendCall = true; SetText("Wysłano żądanie nawiązania połączenia z " + clientName + "\n"); } else { SetText("Nie wybrano klienta\n"); } } if (isConnectedToControlCloud) { if ((String)selectedClientBox.SelectedItem != null) { String clientName = (String)selectedClientBox.SelectedItem; if (!userDict.ContainsKey(clientName)) userDict.Add(clientName, new Address(0, 0, 0)); userToBeCalled = clientName; lastCalledUser = clientName; List<String> _msgList = new List<String>(); _msgList.Add("REQ_CALL"); _msgList.Add(userToBeCalled); _msgList.Add((string)clientSpeedBox.SelectedItem.ToString()); SPacket welcomePacket = new SPacket(myAddress.ToString(), new Address(1, 0, 2).ToString(), _msgList); whatToSendQueue.Enqueue(welcomePacket); } else { SetText("Nie wybrano klienta\n"); } } }
private void setUsernameButton_Click(object sender, EventArgs e) { if (!usernameField.Text.Equals("")) { if (isConnectedToControlCloud) { if (Regex.IsMatch(usernameField.Text, "^[a-zA-Z0-9_]+$")) { username = usernameField.Text; List<String> _msgList = new List<String>(); _msgList.Add("LOGIN"); _msgList.Add(myAddress.ToString()); _msgList.Add(username); SPacket welcomePacket = new SPacket(myAddress.ToString(), new Address(1, 0, 2).ToString(), _msgList); whatToSendQueue.Enqueue(welcomePacket); SetText("Nazwa klienta ustawiona jako " + username + "\n"); } else SetText("Połącz z chmurą zarządania!\n"); } else this.SetText("Dawaj jakąś ludzką nazwę (dozwolone tylko litery, cyfry i znak '_')\n"); } else { SetText("Najpierw połącz się z chmurą sterowania!\n"); isClientNameSet = false; } }
private void sendButton_Click(object sender, EventArgs e) { try { Address source = new Address(int.Parse(srcNet.Text), int.Parse(srcSubnet.Text), int.Parse(srcHost.Text)); Address destination = new Address(int.Parse(destNet.Text), int.Parse(destSubnet.Text), int.Parse(destHost.Text)); SPacket packet = new SPacket(source.ToString(), destination.ToString(), msg.Text); whatToSendQueue.Enqueue(packet); } catch { SetText("Nie wysłało"); } }
/// <summary> /// wątek odbierający wiadomości z chmury /// </summary> public void receiver() { while (isConnectedToCloud) { BinaryFormatter bf = new BinaryFormatter(); try { SPacket receivedPacket = (Packet.SPacket)bf.Deserialize(networkStream); if (isDebug) SetText("Odczytano:\n" + receivedPacket.ToString()); List<String> _msgList = receivedPacket.getParames(); Address _senderAddr; if (Address.TryParse(receivedPacket.getSrc(), out _senderAddr)) { //gdy logowanie się if (_msgList[0] == "HELLO") { try { string usr = _msgList[1]; Address usrAddr = _senderAddr; bool tempIsOk = true; UserData tempUser = null; //SPRAWDZA CZY TAKI JUZ JEST foreach (UserData ud in userList) { if ((ud.userName == usr || ud.userAddr.ToString() == _senderAddr.ToString())) { tempIsOk = false; tempUser = ud; } } if (tempIsOk) { userList.Add(new UserData(usr, usrAddr, 6, true)); List<string> userNames = new List<string>(); foreach(UserData us in userList) { userNames.Add(us.userName); } BindingSource bs = new BindingSource(); bs.DataSource = userNames; this.Invoke((MethodInvoker)delegate() { selectedUserBox.DataSource = bs; }); SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "OK"); whatToSendQueue.Enqueue(pck); } else { SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "NAME_OR_ADDR_TAKEN_BY " + tempUser.userName + " WITH_ADDR " + tempUser.userAddr); whatToSendQueue.Enqueue(pck); } } catch { SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "ERROR"); whatToSendQueue.Enqueue(pck); } //gdy żądanie listy klientów } else if (_msgList[0] == "REQ_CONN") { try { foreach (UserData u in userList) { SPacket pck = new SPacket(myAddr.ToString(), u.userAddr.ToString(), "REQ_VPATHS"); whatToSendQueue.Enqueue(pck); } } catch { SetText("Cos walnelo przy żadaniu VP"); } //Z NCC if (_senderAddr.ToString() == NCCAddr.ToString()) { try { string src = _msgList[1]; string dest = _msgList[2]; string connId = _msgList[3]; SPacket pck; var conn = from c in myConnections where c.connId == Convert.ToInt32(connId) select c; if(conn.Any()) { foreach(var c in conn) try { foreach (UserData us in c.connNodes) { foreach (NodeMapping nm in us.userMappings) { try { string msg; if (nm.outcomingAddr == "-" && nm.outcomingVP == "-" && nm.outcomingVC == "-") { msg = "DEL_MAPPING " + nm.incomingAddr + " " + nm.incomingVP + " " + nm.incomingVC; } else { msg = "DEL_MAPPING " + nm.incomingAddr + " " + nm.incomingVP + " " + nm.incomingVC + " " + nm.outcomingAddr + " " + nm.outcomingVP + " " + nm.outcomingVC; } pck = new SPacket(myAddr.ToString(), us.userAddr.ToString(), msg); whatToSendQueue.Enqueue(pck); deleteVirtualConnection(us, nm.outcomingVP, nm.outcomingVC, nm.outcomingAddr); } catch { SetText("Error sending DEL mapping"); } } } } catch { SetText("Error whilst disconnecting existing connection, resto case"); } } currConnection = new ConnectionRequest(src, dest, Convert.ToInt32(connId)); currConnection.prevCCAddr = NCCAddr.ToString(); awaitingConnections.Add(currConnection); //while (awaitingConnections.Count() != 0) //{ //ConnectionRequest temp = awaitingConnections[awaitingConnections.Count() - 1]; pck = new SPacket(myAddr.ToString(), myRCAddr.ToString(), "REQ_ROUTE " + src + " " + dest); whatToSendQueue.Enqueue(pck); //awaitingConnections.Remove(temp); //} } catch { SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "REQ_CONN z NCC ma za mało danych?"); whatToSendQueue.Enqueue(pck); } } // Z CC else { try { int connId = Convert.ToInt32(_msgList[1]); string incomingAddr = _msgList[2]; string src = _msgList[3]; string vp = _msgList[4]; string vc = _msgList[5]; string dest = _msgList[6]; SPacket pck; var conn = from c in myConnections where c.connId == Convert.ToInt32(connId) select c; if (conn.Any()) { foreach (var c in conn) try { foreach (UserData us in c.connNodes) { foreach (NodeMapping nm in us.userMappings) { try { string msg; if (nm.outcomingAddr == "-" && nm.outcomingVP == "-" && nm.outcomingVC == "-") { msg = "DEL_MAPPING " + nm.incomingAddr + " " + nm.incomingVP + " " + nm.incomingVC; } else { msg = "DEL_MAPPING " + nm.incomingAddr + " " + nm.incomingVP + " " + nm.incomingVC + " " + nm.outcomingAddr + " " + nm.outcomingVP + " " + nm.outcomingVC; } pck = new SPacket(myAddr.ToString(), us.userAddr.ToString(), msg); whatToSendQueue.Enqueue(pck); deleteVirtualConnection(us, nm.outcomingVP, nm.outcomingVC, nm.outcomingAddr); } catch { SetText("Error sending DEL mapping"); } } } } catch { SetText("Error whilst disconnecting existing connection, resto case"); } } currConnection = new ConnectionRequest(src, dest, connId); currConnection.incomingAddr = incomingAddr; currConnection.inVP = Convert.ToInt32(vp); currConnection.inVC = Convert.ToInt32(vc); currConnection.prevCCAddr = _senderAddr.ToString(); UserData tempUser = null; bool userFound = false; foreach (UserData us in userList) { if (us.userAddr.ToString() == src) { tempUser = us; userFound = true; break; } } if(userFound) { //DODANE ALE NIE WYSŁANE, WYSYŁA DOPIERO PO OTRZYMANIU ROUTE OD RC BO TRZEBA DOKLEIC RESZTE MAPOWANIA tempUser.userMappings.Add(new NodeMapping(incomingAddr, vp, vc, "-", "-", "-", connId)); } pck = new SPacket(myAddr.ToString(), myRCAddr.ToString(), "REQ_ROUTE " + src + " " + dest); whatToSendQueue.Enqueue(pck); } catch { SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "REQ_CONN z innego CC ma za mało danych?"); whatToSendQueue.Enqueue(pck); } } } else if(_msgList[0] == "REQ_DISCONN") { int connId = Convert.ToInt32(_msgList[1]); ConnectionRequest connToDis = null; foreach(ConnectionRequest cr in myConnections) { if(cr.connId == connId && cr.active == true) connToDis = cr; } if (connToDis != null) { try { foreach(UserData us in connToDis.connNodes) { foreach(NodeMapping nm in us.userMappings) { try { string msg; if (nm.outcomingAddr == "-" && nm.outcomingVP == "-" && nm.outcomingVC == "-") { msg = "DEL_MAPPING " + nm.incomingAddr + " " + nm.incomingVP + " " + nm.incomingVC; } else { msg = "DEL_MAPPING " + nm.incomingAddr + " " + nm.incomingVP + " " + nm.incomingVC + " " + nm.outcomingAddr + " " + nm.outcomingVP + " " + nm.outcomingVC; } SPacket pck = new SPacket(myAddr.ToString(), us.userAddr.ToString(), msg); whatToSendQueue.Enqueue(pck); deleteVirtualConnection(us, nm.outcomingVP, nm.outcomingVC, nm.outcomingAddr); }catch{ SetText("Error sending DEL mapping"); } } } } catch { SetText("Error whilst disconnecting connection"); } if(connToDis.nextCCAddr != "-") try { SPacket pck = new SPacket(myAddr.ToString(), connToDis.nextCCAddr, "REQ_DISCONN " + connToDis.connId); whatToSendQueue.Enqueue(pck); connToDis.active = false; } catch { SetText("DEL NIE POSZEDL DO NEXTCC"); } else { try { SPacket pck = new SPacket(myAddr.ToString(), NCCAddr.ToString(), "CONN_DISCONN " + connToDis.connId); whatToSendQueue.Enqueue(pck); connToDis.active = false; } catch { SetText("NCC NIE OTRZYMAŁ POTWIERDZENIA DISCONN"); } } } } else if(_msgList[0] == "ROUTE" && _senderAddr.ToString() == myRCAddr.ToString()) { try { UserData prevTempUser = null; for (int i = 1; i < _msgList.Count(); i++ ) { UserData tempUser = null; NodeMapping foundMapping = null; NodeMapping newMapping = null; bool userFound = false; string s = _msgList[i]; foreach(UserData us in userList) { if(us.userAddr.ToString() == s) { tempUser = us; userFound = true; break; } } try { string prev_s = null; string next_s = null; if(i > 0) prev_s = _msgList[i - 1]; if((i+1) < _msgList.Count()) next_s = _msgList[i + 1]; if (!s.Contains('*')) { if (s.Contains(netNum + "." + subNetNum)) { if (userFound) { if (i == 1) { try { if (tempUser.userMappings.Count() != 0) { foreach (NodeMapping nm in tempUser.userMappings) { if (nm.outcomingAddr == "-" && nm.incomingAddr != "-" && nm.toSend == true && nm.callId == currConnection.connId) { foundMapping = nm; } } } } catch { SetText("Something wrong with CC mapping format [error while finding non-complete mapping but mapping is there...]"); } try { if (foundMapping == null && tempUser.userAddr.ToString() != currConnection.destAddr)//DZWONIACY CLIENTX { string newVPI = nextVirtualPath(null, tempUser, next_s); string newVCI = nextVirtualConnection(null, tempUser, newVPI, next_s); newMapping = new NodeMapping(next_s, newVPI, newVCI, "-", "-", "-", currConnection.connId); } else if (foundMapping != null && tempUser.userAddr.ToString() != currConnection.destAddr) //PIERWSZY NODE W NOWEJ PODSIECI { //NodeMapping prevMapping = prevTempUser.userMappings[prevTempUser.userMappings.Count() - 1]; string newVPI = nextVirtualPath(null, tempUser, next_s); string newVCI = nextVirtualConnection(foundMapping, tempUser, newVPI, next_s); //BLEDNE MAPOWANIE 1 W NOWYM NODE DO SPRAWDZENIA!!!! foundMapping.outcomingAddr = next_s; foundMapping.outcomingVP = newVPI; foundMapping.outcomingVC = newVCI; } /*else if (foundMapping != null && tempUser.userAddr.ToString() == currConnection.destAddr)//PIERWSZY NODE W NOWEJ PODSIECI I OSTATNI W POŁĄCZENIU { NodeMapping prevMapping = tempUser.userMappings[tempUser.userMappings.Count() - 1]; //NodeMapping prevMapping = null; //if (prevTempUser.userMappings.Count() > 0) // prevMapping = prevTempUser.userMappings[prevTempUser.userMappings.Count() - 1]; newMapping = new NodeMapping(prev_s, prevMapping.outcomingVP, prevMapping.outcomingVC, "-", "-", "-", currConnection.connId); currConnection.established = true; }*/ } catch(Exception e) { SetText("Error while operating on first ROUTE command member..., Exception " + e.ToString()); } }//KONIEC PIERWSZEGO ADRESU Z ROUTE'A else{ try { if (tempUser.userAddr.ToString() == currConnection.destAddr && !tempUser.userAddr.ToString().Equals(prevTempUser.userAddr.ToString()))//NIE PIERWSZY W ROUTE ALE OSTATNI W POŁĄCZENIU I NIE TEN SAM CO WCZESNIEJ { try { NodeMapping prevMapping = prevTempUser.userMappings[prevTempUser.userMappings.Count() - 1]; string outvpi = null; if (prevMapping.outcomingVP == "-") outvpi = prevMapping.incomingVP; else outvpi = prevMapping.outcomingVP; string outvci = null; if (prevMapping.outcomingVP == "-") outvci = prevMapping.incomingVC; else outvci = prevMapping.outcomingVC; newMapping = new NodeMapping(prev_s, outvpi, outvci, "-", "-", "-", currConnection.connId); currConnection.established = true; } catch(Exception e) { SetText("Error from not first in ROUTE but last in connection, node " + s + ", error: " + e.ToString()); } } else //NODIX GDZIEŚ POMIĘDZY, MA WEJŚCIE I WYJŚCIE { try { NodeMapping prevMapping = prevTempUser.userMappings[prevTempUser.userMappings.Count() - 1]; string newVPI = nextVirtualPath(prevMapping, tempUser, next_s); string newVCI = nextVirtualConnection(prevMapping, tempUser, newVPI, next_s); string outvpi = null; if (prevMapping.outcomingVP == "-") outvpi = prevMapping.incomingVP; else outvpi = prevMapping.outcomingVP; string outvci = null; if (prevMapping.outcomingVP == "-") outvci = prevMapping.incomingVC; else outvci = prevMapping.outcomingVC; newMapping = new NodeMapping(prev_s, outvpi, outvci, next_s, newVPI, newVCI, currConnection.connId); } catch(Exception e) { SetText("Error from transit node: " + s + "Exception e: " + e.ToString()); } } } catch { SetText("Error while operating on not-first members of ROUTE command"); } } try { if (newMapping != null) { tempUser.userMappings.Add(newMapping); prevTempUser = tempUser; } else if (foundMapping != null) { prevTempUser = tempUser; } } catch { SetText("Error while adding newMapping to current NODE"); } currConnection.connNodes.Add(tempUser); //TU ZAMKNIJ } else SetText("Error while operating on ROUTE, there is no connected client having address: " + s); } else { //PIERWSZY NIE Z GWIAZDKA I OSTATNI W OGOLE CZYLI NODE Z NEXT SUBNET currConnection.outNodeAddr = prev_s; currConnection.inNodeAddr = s; NodeMapping prevMapping = prevTempUser.userMappings[prevTempUser.userMappings.Count() - 1]; //string newVPI = nextVirtualPath(prevMapping, tempUser, next_s); //TU_VP currConnection.outVP = Convert.ToInt32(prevMapping.outcomingVP); currConnection.outVC = Convert.ToInt32(prevMapping.outcomingVC); } } else { //TU ZŁAPIE SIĘ TYLKO PIERWSZY Z GWIAZDKA I SUPER BO PRZEKSZTALCAMY GWIAZDKE NA 1 I MAMY NOWY CC DO KTOREGO WYSYLAMY REQ_CONN currConnection.nextCCAddr = s.Replace('*', '1'); break; } } catch(Exception e) { SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "Nie wyszło " + e.ToString()); whatToSendQueue.Enqueue(pck); } } //ROZESLIJ WSZELKIE OCZEKUJACE MAPPINGI DO NODE'ÓW sendMappingsToNodes(); if (currConnection.inNodeAddr != "-" && currConnection.outNodeAddr != "-" && currConnection.nextCCAddr != "-") sendToNextSubnet(); if(currConnection.established == true) { SPacket pck = new SPacket(myAddr.ToString(), NCCAddr.ToString(), "CONN_EST " + currConnection.connId); whatToSendQueue.Enqueue(pck); } myConnections.Add(currConnection); } catch(Exception e) { SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "ROUTE ERROR PODLACZYŁEŚ JAKIEŚ KLIENTY DEBILU? " + e.ToString()); whatToSendQueue.Enqueue(pck); } } else if (_msgList[0] == "ROUTE_NOT_FOUND") { } else if(_msgList[0] == "RES_VPATHS") { try { receiveVirtualPaths(_msgList, _senderAddr.ToString()); } catch { SetText("Error whilst receiving VPATHS..."); } } else if(_msgList[0] == "DEAD") { string deadAddr = _msgList[1]; List<ConnectionRequest> toRestoreConns = new List<ConnectionRequest>(); foreach(ConnectionRequest cr in myConnections) { foreach(UserData ud in cr.connNodes) { foreach (NodeMapping nm in ud.userMappings) { if (nm.incomingAddr.Equals(deadAddr) || nm.outcomingAddr.Equals(deadAddr)) { var conn = from c in toRestoreConns where c.connId == cr.connId select c; if(!conn.Any()) toRestoreConns.Add(cr); } } } } /*try { foreach (ConnectionRequest cr in toRestoreConns) { foreach (UserData us in cr.connNodes) { foreach (NodeMapping nm in us.userMappings) { try { string msg = "DEL_MAPPING " + nm.incomingAddr + " " + nm.incomingVP + " " + nm.incomingVC + " " + nm.outcomingAddr + " " + nm.outcomingVP + " " + nm.outcomingVC; SPacket pck = new SPacket(myAddr.ToString(), us.userAddr.ToString(), msg); whatToSendQueue.Enqueue(pck); deleteVirtualConnection(us, nm.outcomingVP, nm.outcomingVC, nm.outcomingAddr); } catch { SetText("Error sending DEL mapping in DEAD section"); } } } try { string secParam = null; if(cr.outNodeAddr == "-") { secParam = cr.srcAddr; } else { secParam = cr.inNodeAddr; } SPacket pck; if (cr.prevCCAddr == NCCAddr.ToString()) { // SPacket pck = new SPacket(myAddr.ToString(), myRCAddr.ToString(), "REQ_ROUTE " + cr.srcAddr + " " + secParam); pck = new SPacket(cr.prevCCAddr, myAddr.ToString(), "REQ_CONN " + cr.srcAddr + " " + cr.destAddr + " " + cr.connId); }else{ pck = new SPacket(myAddr.ToString(), cr.prevCCAddr, "REQ_CONN " + cr.connId + " " + cr.outNodeAddr + " " + cr.outVP + " " + cr.outVC + " " + cr.destAddr); } whatToSendQueue.Enqueue(pck); } catch { SetText("Error whilst sending request to RC for restoring in-domain route"); } } } catch { SetText("Error whilst disconnecting connection"); } */ try { foreach (ConnectionRequest cr in toRestoreConns) { try { string msg = null; if(cr.prevCCAddr == "1.0.2") { msg = "REQ_CONN " + cr.srcAddr + " " + cr.destAddr + " " + cr.connId; } else { msg = "REQ_CONN " + cr.connId + " " + cr.incomingAddr + " " + cr.srcAddr + " " + cr.inVP + " " + cr.inVC + " " + cr.destAddr; } SPacket pck = new SPacket(cr.prevCCAddr, myAddr.ToString(), msg); whatToSendQueue.Enqueue(pck); } catch { SetText("Error sending DEL mapping in DEAD section"); } } } catch { SetText("Error whilst connection restoration"); } //SetText(""); //DISCONNECT SASIEDNIE WEZLY ZMAPOWANE //SPacket pck = new SPacket(myAddr.ToString(), "0.0.2", "REQ_CONN ); //whatToSendQueue.Enqueue(pck); } /*else if (_msgList[0] == "REQ_SRC") { int id = Convert.ToInt32(_msgList[1]); var conn = from c in myConnections where c.connId == id select c; if(conn.Any()){ foreach(var c in conn) { SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "MY_SRC " + c.srcAddr); whatToSendQueue.Enqueue(pck); } } }*/ } } catch { SetText("Coś poszło nie tak"); } } }
public void wyslijSPacket(Packet.SPacket cos)//wysyłanie przez chmurę kablową { parent.whatToSendQueue.Enqueue(cos); }
/// <summary> /// wątek odbierający wiadomości z chmury /// </summary> public void receiver() { while (isConnectedToCloud) { BinaryFormatter bf = new BinaryFormatter(); try { SPacket receivedPacket = (Packet.SPacket)bf.Deserialize(networkStream); if (isDebug) SetText("Odczytano:\n" + receivedPacket.ToString()); List<String> _msgList = receivedPacket.getParames(); Address _senderAddr; if (Address.TryParse(receivedPacket.getSrc(), out _senderAddr)) { //gdy logowanie się if (_msgList[0] == "LOGIN") { try { Address usrAddr = Address.Parse(_msgList[1]); string usr = _msgList[2]; bool tempIsOk = true; userData tempUser = null; foreach (userData ud in userList) { if (ud.userName == usr /*|| ud.userAddr.ToString() == _senderAddr.ToString()*/) { tempIsOk = false; tempUser = ud; } } if (tempIsOk) { userList.Add(new userData(usr, usrAddr, 6, true)); List<string> temp = new List<string>(); foreach (userData ud in userList) { temp.Add(ud.userName); } BindingSource bs = new BindingSource(); bs.DataSource = temp; this.Invoke((MethodInvoker)delegate() { selectedClientBox.DataSource = bs; }); List<string> _msg = new List<string>(); _msg.Add("LOGGED"); _msg.Add(usrAddr.ToString()); _msg.Add(usr); SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), _msg); whatToSendQueue.Enqueue(pck); this.Invoke((MethodInvoker)delegate() { selectedClientBox_SelectedIndexChanged(); }); } else { List<string> _msg = new List<string>(); _msg.Add("NAME_TAKEN"); _msg.Add(usrAddr.ToString()); _msg.Add(usr); SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), _msg); whatToSendQueue.Enqueue(pck); } } catch { SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "ERROR"); whatToSendQueue.Enqueue(pck); } //gdy żądanie listy klientów } else if (_msgList[0] == "REQ_CLIENTS") { List<string> clients = new List<string>(); clients.Add("CLIENTS"); clients.Add(_msgList[1]); String callerName = String.Empty; /* foreach (userData ud in userList) { if (ud.userAddr == _senderAddr) { callerName = ud.userName; } }*/ foreach (userData ud in userList) { //if (ud.userName != callerName) { clients.Add(ud.userName); //} } SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), clients); whatToSendQueue.Enqueue(pck); //gdy żądanie połączenia } else if (_msgList[0] == "REQ_CALL") { try { Address usrAddr = Address.Parse(_msgList[1]); bool canCall = false; foreach (userData ud in userList) { if (ud.userAddr.ToString() == usrAddr.ToString()) { if (ud.canReq && int.Parse(_msgList[3]) <= ud.userCap) canCall = true; } } List<string> response = new List<string>(); if (canCall) { foreach (userData ud in userList) { if (ud.userName == _msgList[2]) { response.Add("OK"); response.Add(usrAddr.ToString()); response.Add(ud.userName); response.Add(_msgList[3]); response.Add(ud.userAddr.ToString()); } } } else { response.Add("NO"); response.Add(usrAddr.ToString()); response.Add(_msgList[2]); response.Add(_msgList[3]); } SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), response); whatToSendQueue.Enqueue(pck); } catch { SPacket pck = new SPacket(myAddr.ToString(), _senderAddr.ToString(), "ERROR"); whatToSendQueue.Enqueue(pck); } } } } catch { SetText("Coś poszło nie tak"); if (++exceptionCount == 5) { this.Invoke((MethodInvoker)delegate() { isConnectedToCloud = false; conToCloudButton.Text = "Połącz"; SetText("Rozłączono!"); if (cloudSocket != null) cloudSocket.Close(); }); } } } }
public void OdczytajS(Packet.SPacket cos)//odbieranie z chmury kablowej { kolejkaS.Enqueue(cos); }
public void sendMappingsToNodes() { foreach (UserData us in userList) { foreach (NodeMapping nodeMapping in us.userMappings) { if (nodeMapping.toSend == true) try { string msg = null; if (nodeMapping.outcomingAddr == "-" && nodeMapping.outcomingVP == "-" && nodeMapping.outcomingVC == "-") { /*var mapping = from m in us.userMappings where (m.incomingAddr.Equals(nodeMapping.incomingAddr) && m.incomingVP.Equals(nodeMapping.incomingVP) && m.incomingVC.Equals(nodeMapping.incomingVC) && m.outcomingAddr.Equals("-") && m.incomingVP.Equals("-") && m.incomingVC.Equals("-")) select m; if(!mapping.Any())*/ msg = "ADD_MAPPING " + nodeMapping.incomingAddr + " " + nodeMapping.incomingVP + " " + nodeMapping.incomingVC + " " + nodeMapping.callId; } else { /*var mapping = from m in us.userMappings where (m.incomingAddr.Equals(nodeMapping.incomingAddr) && m.incomingVP.Equals(nodeMapping.incomingVP) && m.incomingVC.Equals(nodeMapping.incomingVC) && m.outcomingAddr.Equals(nodeMapping.outcomingAddr) && m.outcomingVP.Equals(nodeMapping.outcomingVP) && m.outcomingVC.Equals(nodeMapping.outcomingVC)) select m; if(!mapping.Any())*/ msg = "ADD_MAPPING " + nodeMapping.incomingAddr + " " + nodeMapping.incomingVP + " " + nodeMapping.incomingVC + " " + nodeMapping.outcomingAddr + " " + nodeMapping.outcomingVP + " " + nodeMapping.outcomingVC; } SPacket pck = new SPacket(myAddr.ToString(), us.userAddr.ToString(), msg); whatToSendQueue.Enqueue(pck); nodeMapping.toSend = false; } catch { SetText("Error while sending mappings..."); } } } }