private void RemovePeerFromDictionaries(PeerData peer, string reason) { if (peer != null) { if (PeersTx.ContainsKey(peer.SubnetworkIP)) { PeersTx.Remove(peer.SubnetworkIP); } if (PeersRxSupport.ContainsKey(peer.GetSupportEndpoint())) { PeersRxSupport.Remove(peer.GetSupportEndpoint()); } if (PeersRxTransmission.ContainsKey(peer.GetSupportEndpoint())) { PeersRxTransmission.Remove(peer.GetTransmissionEndpoint()); } OnPeerListChanged(this, new PeerListChangedEventArgs(PeersRxSupport.Values.ToArray())); if (reason != null) { Logger.Instance.LogMsg("Usunięto użytkownika (" + reason + "): " + peer.ToString()); } else { Logger.Instance.LogMsg("Usunięto użytkownika: " + peer.ToString()); } } }
private void addOrUpdatePeerToRoster(JObject peerData) { Debug.WriteLine("addOrUpdatePeerToRoster " + peerData); string serverId = (string)peerData["id"]; PeerData peer = null; if (_roster.ContainsKey(serverId)) { peer = _roster[serverId]; } else { peer = new PeerData(); } peer.name = (string)peerData["name"]; peer.localIntId = serverId.GetHashCode(); peer.online = (bool)peerData["online"]; peer.serverId = (string)peerData["id"]; peer.token = (string)peerData["token"]; peer.type = (string)peerData["type"]; peer.user = (string)peerData["user"]; if (!_roster.ContainsKey(serverId)) { _roster.Add(peer.serverId, peer); _localIntIdsToServerIds.Add(peer.localIntId, peer.serverId); RaiseOnPeerConnected(peer.localIntId, peer.user); } }
public override async Task <bool> SendToPeer(int peerId, string message) { Debug.WriteLine("SympleSignaller:SendToPeer string: " + peerId + " " + message); Debug.Assert(IsConnected()); if (!IsConnected()) { return(false); } if (_localIntIdsToServerIds.ContainsKey(peerId)) { string peerServerId = _localIntIdsToServerIds[peerId]; PeerData recipientPeerData = _roster[peerServerId]; Debug.WriteLine("original message: " + message); JObject parameters = new JObject(); parameters["to"] = peerDataToJObject(recipientPeerData); parameters["type"] = "message"; parameters["misc_message"] = message; // TODO: not doing anything meaningful with the "BYE" message that PeerCC sends send(parameters); return(true); } else { Debug.WriteLine("attempted SendToPeer on unknown peer id " + peerId); throw new NotImplementedException(); } throw new NotImplementedException(); }
private void onConnect(long peerId) { Debug.Assert(!peerToCodec.ContainsKey(peerId)); var data = new PeerData(); peerToCodec[peerId] = data; Global.RoomPID.Tell(new RoomCmdEnter { peerId = peerId }); data.codec.FrameCb = frame => { try { var msg = PBSerializer.Deserialize(typeDb, frame); Global.RoomPID.Tell(new RoomCmdMsg { msg = msg, peerId = peerId }); } catch (Exception e) { this.Fatal(e.ToString()); } }; }
private void SocketOnAnnounced(object resObj) { Debug.WriteLine("TODO: SocketOnAnnounced"); JObject res = (JObject)resObj; if ((int)res["status"] != 200) { // authentication error RaiseOnServerConnectionFailure(); return; } JObject myPeerData = (JObject)res["data"]; Debug.WriteLine("myPeerData: " + myPeerData.ToString()); string serverId = (string)myPeerData["id"]; addOrUpdatePeerToRoster(myPeerData); _myPeerData = _roster[serverId]; JObject sendPresenceParams = new JObject(); sendPresenceParams["probe"] = true; this.sendPresence(sendPresenceParams); _socket.On(Socket.EVENT_MESSAGE, SocketOnMessage); RaiseOnSignedIn(); }
private void StartDriver(Subnetwork subnetwork, uint localIP, string UserName) { CurrentSubnetwork = subnetwork; IP = localIP; BroadcastAddress = subnetwork.Address | ~(subnetwork.CIDR.GetMaskFromCIDR()); Me = new PeerData( UserName, localIP, LocalEndpointSupport.Address.IPToInt(), LocalEndpointSupport.Port, LocalEndpointTransmission.Port, KeyExchange.GetPublicKey() ); AddPeerToDictionaries(Me); try { Driver.SetFilter(subnetwork.Address, subnetwork.CIDR.GetMaskFromCIDR(), localIP); InterfaceConfig.AddIP(localIP, subnetwork.CIDR.GetMaskFromCIDR()); Driver.StartReading(ProcessReceivedDriverData); DriverStarted = true; OnConnected(this, null); } catch { _Connected = false; throw; } }
public static void AddOrUpdate(PeerData contact) { var exists = PeerDataContainer.Containers.Any(s => s.Key == contact.UserId); var contactContainer = exists ? PeerDataContainer.Containers[contact.UserId] : PeerDataContainer.CreateContainer(contact.UserId, ApplicationDataCreateDisposition.Always); contactContainer.Values.AddOrUpdate(nameof(PeerData.Name), contact.Name); contactContainer.Values.AddOrUpdate(nameof(PeerData.Avatar), contact.Avatar); contactContainer.Values.AddOrUpdate(nameof(PeerData.IsOnline), contact.IsOnline); }
internal bool Connect(PeerData peerData) { Logger.GetLog().Debug("次のピアに接続します: " + peerData.PeerId + "(" + peerData.Address + ":" + peerData.Port + ")"); this.PeerData = peerData; bool result = socket.Connect(peerData.Address, peerData.Port); Logger.GetLog().Debug("接続結果: " + result); return(result); }
private void AddPeerToDictionaries(PeerData peer) { if (peer != null) { PeersTx.Add(peer.SubnetworkIP, peer); PeersRxSupport.Add(peer.GetSupportEndpoint(), peer); PeersRxTransmission.Add(peer.GetTransmissionEndpoint(), peer); OnPeerListChanged(this, new PeerListChangedEventArgs(PeersRxSupport.Values.ToArray())); Logger.Instance.LogMsg("Dodano użytkownika: " + peer.ToString()); } }
public SympleSignaller() : base() { _myPeerData = new PeerData(); _roster = new Dictionary <string, PeerData>(); _localIntIdsToServerIds = new Dictionary <int, string>(); // comment these out if not needed Messenger.AddListener <string>(SympleLog.LogTrace, OnLog); Messenger.AddListener <string>(SympleLog.LogDebug, OnLog); Messenger.AddListener <string>(SympleLog.LogInfo, OnLog); Messenger.AddListener <string>(SympleLog.LogError, OnLog); }
private JObject peerDataToJObject(PeerData pd) { JObject p = new JObject(); p["user"] = pd.user; p["name"] = pd.name; p["type"] = pd.type; p["token"] = pd.token; p["id"] = pd.serverId; p["online"] = pd.online; return(p); }
private void EncryptAndSendTransmissionPacket(byte[] data, PeerData peer) { byte[] encryptedData = Encryption.Encrypt(data, peer.KeyIndex); if (encryptedData != null) { UdpTransmission.Send(encryptedData, encryptedData.Length, peer.GetTransmissionEndpoint()); Stats.ULBytes += (ulong)data.Length; Stats.ULPackets++; peer.Stats.ULBytes += (ulong)data.Length; peer.Stats.ULPackets++; } }
private Task InitiateNewUser(PeerData peer, uint subnetworkIP) { return(Task.Run(() => { // pakiet dla nowego użytkownika UdpNewPeerPacket packet = new UdpNewPeerPacket( peer.Name, subnetworkIP, true, PeersRxSupport.Values.ToArray(), CurrentSubnetwork ); byte[] data = GetSerializedBytes <UdpNewPeerPacket>(packet); ReceivedConfirmation = new ManualResetEvent(false); NewPeer = peer; int retryCounter = 0; while (retryCounter++ < ConnectionRetries && !CancelToken.IsCancellationRequested) { UdpSupport.Send(data, data.Length, peer.GetSupportEndpoint()); if (ReceivedConfirmation.WaitOne(2000)) { break; } } NewPeer = null; if (retryCounter > ConnectionRetries) { throw new NewClientNotReachedException("Czas wywołania minął!", null); } if (!CancelToken.IsCancellationRequested) { return; } // pakiet dla pozostałych packet = new UdpNewPeerPacket( null, 0, false, new PeerData[1] { peer }, null ); Broadcast <UdpNewPeerPacket>(packet); })); }
public override async Task <bool> SignOut() { Debug.WriteLine("SympleSignaller:SignOut"); if (_socket != null) { _socket.Disconnect(); _socket.Close(); _socket = null; } _roster.Clear(); _localIntIdsToServerIds.Clear(); _myPeerData = new PeerData(); return(true); }
public async void AddPeer(string ConnectionString, uint SubnetworkIP) { if (!_Connected) { OnAddedPeer(this, new AddedPeerEventArgs(false, new InvalidOperationException("Żadne połączenie nie jest obecnie otwarte."))); return; } if ((SubnetworkIP & CurrentSubnetwork.CIDR.GetMaskFromCIDR()) != CurrentSubnetwork.Address) { OnAddedPeer(this, new AddedPeerEventArgs(false, new InvalidOperationException("Wybrany adres IP jest spoza zakresu możliwych adresów w tej sieci."))); return; } foreach (uint ip in PeersTx.Keys) { if (ip == SubnetworkIP) { OnAddedPeer(this, new AddedPeerEventArgs(false, new InvalidOperationException("Wybrany adres IP jest już przypisany do innego użytkownika. Proszę wybrać inny."))); return; } } if (ConnectionString.IndexOf(URI) > -1) { ConnectionString = ConnectionString.Remove(ConnectionString.IndexOf(URI), URI.Length + 1); } PeerData peer = null; try { Base64PeerData peerData = Base64PeerData.GetBase64PeerData(ConnectionString); peer = PeerData.GetDataFromBase64PeerData(peerData, SubnetworkIP); await InitiateNewUser(peer, SubnetworkIP); OnAddedPeer(this, new AddedPeerEventArgs(true, null)); } catch (Exception ex) { RemovePeerFromDictionaries(peer, null); OnAddedPeer(this, new AddedPeerEventArgs(false, ex)); } }
public bool Connect(PeerData peerData) { Peer peer = new Peer(this); peer.Closed += new EventHandler(Peer_Closed); peer.ReadLine += new EventHandler <ReadLineEventArgs>(Peer_ReadLine); peer.PeerId += () => { return(PeerId()); }; bool result = peer.Connect(peerData); if (result) { peerList.Add(peer); ConnectionsChanged(this, EventArgs.Empty); } return(result); }
private void ProcessReceivedDriverData(byte[] data) { if (data.Length < 20) { return; } uint sendTo = BitConverter.ToUInt32(data, 16).InvertBytes(); PeerData peer = null; if (sendTo == BroadcastAddress) { BroadcastTransmissionPacket(data); } else if (PeersTx.TryGetValue(sendTo, out peer)) { EncryptAndSendTransmissionPacket(data, peer); } }
private void NegotiateKey(PeerData peer, UdpKeyNegotiationPacket packet) { if (!peer.KeyExchangeInProgress) { UdpKeyNegotiationPacket negoPacket = new UdpKeyNegotiationPacket( KeyExchange.GetKeyMaterial(), KeyExchange.GetDSASignature() ); SendPacket <UdpKeyNegotiationPacket>(negoPacket, peer.GetSupportEndpoint()); } if (packet != null) { Encryption.DeleteKeyIfInStore(peer.KeyIndex); peer.KeyIndex = Encryption.AddKeyToStore( KeyExchange.GetDerivedKey(packet.KeyMaterial, packet.DSASignature, peer.PublicKey) ); peer.KeyExchangeInProgress = false; } else { peer.KeyExchangeInProgress = true; } }
void Update() { int recHostId; int recConnectionId; int dataSize; byte error; NetworkEventType recData = NetworkTransport.Receive(out recHostId, out recConnectionId, out channelId, recBuffer, recBuffer.Length, out dataSize, out error); switch (recData) { case NetworkEventType.Nothing: break; case NetworkEventType.ConnectEvent: Debug.Log("Connected"); CreateProcessManager(recConnectionId); MemoryStream sendstream2 = new MemoryStream(); sendstream2.WriteByte(MESSAGE_GET_PEERS); new BinaryFormatter().Serialize(sendstream2, localProcessManager.peerId); byte[] b2 = sendstream2.ToArray(); NetworkTransport.Send(hostId, recConnectionId, channelId, b2, b2.Length, out error); break; case NetworkEventType.DataEvent: //Debug.Log ("DATA "+dataSize); MemoryStream stream = new MemoryStream(recBuffer, 0, dataSize); byte type = (byte)stream.ReadByte(); switch (type) { case MESSAGE_PROCESS_LIST: Dictionary <int, ProcessData> processes = (Dictionary <int, ProcessData>) new BinaryFormatter().Deserialize(stream); playerProcessManagers[recConnectionId].UpdateProcesses(processes); break; case MESSAGE_KILL_PROCESS: int processId = (int)new BinaryFormatter().Deserialize(stream); KillLocalProcess(processId); break; case MESSAGE_GET_PEERS: Debug.LogError("Send peer list"); int remotePeerId = (int)new BinaryFormatter().Deserialize(stream); foreach (KeyValuePair <int, PlayerProcessManager> player in playerProcessManagers) { if (remotePeerId == player.Value.peerId) { Debug.LogError("Duplicate connection " + recConnectionId + " with player " + player.Key + " detected, disconnect"); NetworkTransport.Disconnect(hostId, recConnectionId, out error); } } playerProcessManagers[recConnectionId].peerId = remotePeerId; Dictionary <int, PeerData> peers = new Dictionary <int, PeerData>(); foreach (KeyValuePair <int, PlayerProcessManager> player in playerProcessManagers) { if (player.Key == 0) { continue; // ignore local player } if (player.Key == recConnectionId) { continue; // ignore remote player } PeerData peer = new PeerData(); UnityEngine.Networking.Types.NetworkID network; UnityEngine.Networking.Types.NodeID dstNode; NetworkTransport.GetConnectionInfo(hostId, player.Key, out peer.address, out peer.port, out network, out dstNode, out error); peers.Add(player.Key, peer); } MemoryStream sendstream = new MemoryStream(); sendstream.WriteByte(MESSAGE_PEERS); new BinaryFormatter().Serialize(sendstream, peers); byte[] b = sendstream.ToArray(); NetworkTransport.Send(hostId, recConnectionId, channelId, b, b.Length, out error); break; case MESSAGE_PEERS: Debug.LogError("Recieve peer list"); Dictionary <int, PeerData> remotepeers = (Dictionary <int, PeerData>) new BinaryFormatter().Deserialize(stream); foreach (KeyValuePair <int, PeerData> peer in remotepeers) { Debug.LogError("Connect to peer: " + peer.Value.address + ":" + peer.Value.port); NetworkTransport.Connect(hostId, peer.Value.address, peer.Value.port, 0, out error); } break; } break; case NetworkEventType.DisconnectEvent: Debug.Log("Disconnected"); DestroyProcessManager(recConnectionId); break; } if (Input.GetKeyDown(KeyCode.C)) { StartClient(); } }
private void SocketOnMessage(object msg) { Messenger.Broadcast(SympleLog.LogTrace, "SocketOnMessage: " + msg); JObject m = (JObject)msg; string mType = (string)m["type"]; switch (mType) { case "message": break; case "command": break; case "event": break; case "presence": JObject remotePeerData = (JObject)m["data"]; // data about another peer that has been updated or removed bool remotePeerOnline = (bool)remotePeerData["online"]; if (remotePeerOnline) { addOrUpdatePeerToRoster(remotePeerData); } else { string remotePeerServerId = (string)remotePeerData["id"]; removePeerFromRoster(remotePeerServerId); } if (m["probe"] != null && (bool)m["probe"] == true) { JObject presenceTo = new JObject(); presenceTo["to"] = Symple.parseAddress(m["from"].ToString())["id"]; this.sendPresence(presenceTo); } break; default: m["type"] = m["type"] ?? "message"; break; } if (m["from"].Type != JTokenType.String) { Messenger.Broadcast(SympleLog.LogError, "symple:client: invalid sender address: " + m); return; } // replace the from attribute with the full peer object. // this will only work for peer messages, not server messages. string mFrom = (string)m["from"]; Messenger.Broadcast(SympleLog.LogTrace, "looking up rpeer in roster, mFrom = " + mFrom + "..."); var addr = Symple.parseAddress(mFrom); Debug.WriteLine("addr " + addr); mFrom = (string)addr["id"] ?? mFrom; if (_roster.ContainsKey(mFrom)) { PeerData rpeerData = _roster[mFrom]; Messenger.Broadcast(SympleLog.LogTrace, "found rpeerData: " + rpeerData); m["from"] = peerDataToJObject(rpeerData); } else { Messenger.Broadcast(SympleLog.LogDebug, "symple:client: got message from unknown peer: " + m); } // Dispatch to the application SignallerOnMessage(mType, m); }
private Dictionary <int, string> _localIntIdsToServerIds; // maps local int ids to server ids private void SignallerOnMessage(string mType, JObject m) { Debug.WriteLine("SignallerOnMessage " + mType + " " + m); // here we process what the webrtccontext would normally do when a new message comes in. // so we adjust the message and pass it on to the Conductor. string fromServerId; var mFromObj = m["from"] as JObject; if (mFromObj != null) { fromServerId = (string)mFromObj["id"]; } else { fromServerId = (string)m["from"]; // string instead of json object } JObject parsedAddress = Symple.parseAddress(fromServerId); // handle case where "from" is name|id fromServerId = (string)parsedAddress["id"] ?? fromServerId; if (_roster.ContainsKey(fromServerId)) { PeerData fromPd = _roster[fromServerId]; int fromLocalIntId = fromPd.localIntId; if (m["offer"] != null) { Debug.WriteLine("incoming offer message"); JObject messageForConductor = (JObject)m["offer"]; RaiseOnMessageFromPeer(fromLocalIntId, messageForConductor.ToString(Formatting.None)); } else if (m["answer"] != null) { Debug.WriteLine("incoming answer message"); JObject messageForConductor = (JObject)m["answer"]; RaiseOnMessageFromPeer(fromLocalIntId, messageForConductor.ToString(Formatting.None)); } else if (m["candidate"] != null) { Debug.WriteLine("incoming candidate message"); JObject messageForConductor = (JObject)m["candidate"]; RaiseOnMessageFromPeer(fromLocalIntId, messageForConductor.ToString(Formatting.None)); } else if (mType == "presence") { // the presence messages are handled earlier in the signalling code, so at this point, do nothing with them. } else if (m["message"] != null) { JObject messageForConductor = m; // send the entire raw message! the "message" format will route it correctly RaiseOnMessageFromPeer(fromLocalIntId, messageForConductor.ToString(Formatting.None)); } else { // the content of the message is unrecognized by the signaller Debug.WriteLine("TODO: incoming misc message of type " + m["type"]); } } else { Debug.WriteLine("received message from unknown sender " + fromServerId); } }
private string buildAddress(PeerData pd) { return(Symple.buildAddress(peerDataToJObject(pd))); }
public override async Task <bool> SendToPeer(int peerId, IJsonValue json) { Debug.WriteLine("SympleSignaller:SendToPeer json: " + peerId + " " + json); Debug.Assert(IsConnected()); if (!IsConnected()) { return(false); } if (_localIntIdsToServerIds.ContainsKey(peerId)) { string peerServerId = _localIntIdsToServerIds[peerId]; PeerData recipientPeerData = _roster[peerServerId]; Debug.WriteLine("original IJsonValue: " + json); JObject jsonMessage = JObject.Parse(json.Stringify()); Debug.WriteLine("after conversion to JObject: " + jsonMessage); if (jsonMessage["sdp"] != null) { JObject sessionDesc = jsonMessage; JObject parameters = new JObject(); parameters["to"] = peerDataToJObject(recipientPeerData); parameters["type"] = "message"; string jsonMessageType = (string)jsonMessage["type"]; if (jsonMessageType == "offer") { parameters["offer"] = sessionDesc; } else if (jsonMessageType == "answer") { parameters["answer"] = sessionDesc; } else { Debug.WriteLine("unknown jsonMessageType for sdp: " + jsonMessageType); throw new NotImplementedException(); } send(parameters); return(true); } if (jsonMessage["candidate"] != null) { JObject candidateObj = jsonMessage; JObject parameters = new JObject(); parameters["to"] = peerDataToJObject(recipientPeerData); parameters["type"] = "message"; parameters["candidate"] = candidateObj; send(parameters); return(true); } if (jsonMessage["message"] != null) { // sending a misc. message to the peer. var msgObj = jsonMessage["message"]; // note that we go down one level here JObject parameters = new JObject(); parameters["to"] = peerDataToJObject(recipientPeerData); parameters["type"] = "message"; parameters["message"] = msgObj; send(parameters); return(true); } Debug.WriteLine("unknown message of type " + jsonMessage); throw new NotImplementedException(); } else { Debug.WriteLine("attempted SendToPeer on unknown peer id " + peerId); throw new NotImplementedException(); } }
public bool Connect(PeerData peer) { return(peerManager.Connect(peer)); }
void OnPubNubMessage(string message) { string[] splitMessage = message.Trim().Substring(1, message.Length - 2).Split(new char[] { ',' }); string peerDataMessage = splitMessage[0].Trim().Substring(1, splitMessage[0].Trim().Length - 2); //string peerMessageId = splitMessage[1].Trim().Substring(1, splitMessage[1].Trim().Length - 2); //string room = splitMessage[2].Trim().Substring(1, splitMessage[2].Trim().Length - 2); PeerData peerData = new PeerData(peerDataMessage); // If you are on the same device then you have to do this for it to work if (peerData.localIp == localIp && peerData.externalIp == externalIp) { peerData.localIp = "127.0.0.1"; } // From me, ignore if (peerData.pubNubUniqueId == pubnub.SessionUUID) { return; } if (udpClient == null) { return; } // From someone else // First time we have heard from them if (!uniqueIdsPubNubSeen.Contains(peerData.pubNubUniqueId)) { uniqueIdsPubNubSeen.Add(peerData.pubNubUniqueId); udpClient.Send(new byte[10], 10, new IPEndPoint(IPAddress.Parse(peerData.externalIp), peerData.externalPort)); udpClient.Send(new byte[10], 10, new IPEndPoint(IPAddress.Parse(peerData.localIp), peerData.localPort)); // This is if they are on a LAN, we will try both because why not pubnub.Publish <string>(channelName, (new PeerData(localPort, externalPort, localIp, externalIp, pubnub.SessionUUID)).ToString(), OnPubNubTheyGotMessage, OnPubNubMessageFailed); } // Second time we have heard from them, after then we don't care because we are connected else if (!connectedPeers.ContainsKey(peerData.pubNubUniqueId)) { IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(peerData.externalIp), peerData.externalPort); IPEndPoint endPointLocal = new IPEndPoint(IPAddress.Parse(peerData.localIp), peerData.localPort); //bool isOnLan = IsLanIP(IPAddress.Parse(peerData.externalIp)); TODO, this would be nice to test for bool isOnLan = true; P2PPeer peer = new P2PPeer(peerData.localIp, peerData.externalIp, peerData.localPort, peerData.externalPort, this, isOnLan); lock (peerLock) { connectedPeers.Add(peerData.pubNubUniqueId, peer); } udpClient.Send(new byte[10], 10, endPoint); udpClient.Send(new byte[10], 10, endPointLocal); // This is if they are on a LAN pubnub.Publish <string>(channelName, (new PeerData(localPort, externalPort, localIp, externalIp, pubnub.SessionUUID)).ToString(), OnPubNubTheyGotMessage, OnPubNubMessageFailed); if (OnNewPeerConnection != null) { OnNewPeerConnection(peer); } } }
private void ProcessUdpPacket(CommPacket packet, IPEndPoint ep) { PeerData peer = null; if (packet is UdpConnectingConfirmation) { AddPeerToDictionaries(NewPeer); if (ReceivedConfirmation != null) { ReceivedConfirmation.Set(); } } else if (packet is UdpNewPeerPacket) { UdpNewPeerPacket newPeerPacket = packet as UdpNewPeerPacket; if (newPeerPacket.RecipientIsNew && AwaitingExternalConnection) { AwaitingExternalConnection = false; AddPeersToDictionaries(newPeerPacket.Peers); StartDriver(newPeerPacket.SubnetworkData, newPeerPacket.SubnetworkIP, newPeerPacket.Name); OnConnected(this, null); UdpConnectingConfirmation confirmPacket = new UdpConnectingConfirmation(); SendPacket <UdpConnectingConfirmation>(confirmPacket, ep); Thread.Sleep(100); NegotiateKey(PeersRxSupport[ep], null); } else { if (newPeerPacket.Peers != null && !newPeerPacket.RecipientIsNew) { if (newPeerPacket.Peers.Length != 0) { AddPeerToDictionaries(newPeerPacket.Peers[0]); NegotiateKey(peer, null); } } } } else if (packet is UdpKeyNegotiationPacket) { if (!PeersRxSupport.TryGetValue(ep, out peer)) { peer = NewPeer; } NegotiateKey(peer, packet as UdpKeyNegotiationPacket); } else if (packet is UdpGoodbye) { RemovePeerFromDictionaries(PeersRxSupport[ep], "goodbye"); } else if (packet is UdpHeartbeat) { if (PeersRxSupport.TryGetValue(ep, out peer)) { peer.Heartbeat(); } } }
private void NetworkTransmissionDataCallout(IAsyncResult result) { IPEndPoint ep = new IPEndPoint(IPAddress.Any, 0); try { byte[] data = null; data = UdpTransmission.EndReceive(result, ref ep); if (data == null || data.Length == 0) { return; } PeerData peer = null; if (PeersRxTransmission.TryGetValue(ep, out peer)) { byte[] decryptedData = Encryption.Decrypt(data, peer.KeyIndex); if (decryptedData == null) { Logger.Instance.LogError("Odrzucono niepoprawny pakiet (niezgodność skrótów). Użytkownik: " + peer.Name); } else { Driver.WriteData(decryptedData); Stats.DLBytes += (ulong)decryptedData.Length; Stats.DLPackets++; peer.Stats.DLBytes += (ulong)decryptedData.Length; peer.Stats.DLPackets++; } } if (_Connected) { UdpTransmission.BeginReceive(NetworkTransmissionDataCallout, null); } else { UdpTransmission.Close(); } } catch (Exception ex) { if (ex is SocketException) { int code = ((SocketException)ex).ErrorCode; if (code != 10060 && code != 10004) { MessageBox.Show( "Błąd połączenia: " + ex.Message, "Błąd", MessageBoxButton.OK, MessageBoxImage.Error ); Logger.Instance.LogException(ex); Disconnect(); } } if (!(ex is ObjectDisposedException)) { Logger.Instance.LogException(ex); } if (_Connected) { UdpTransmission.BeginReceive(NetworkTransmissionDataCallout, null); } else { UdpTransmission.Close(); } } }