private void CollectSocket(Socket socket) { ISocket isocket = new TcpSocket(socket, RandomId.Generate()); while (!csockets.TryAdd(isocket.Id, isocket)) { isocket = new TcpSocket(socket, RandomId.Generate()); } isocket.OnSocketDisconnected += RemoveSocket; SendServerToken(isocket); OnConnectionRequested?.Invoke(isocket); }
private void ButtonTargetConnectionStringClick(object sender, EventArgs e) { OnConnectionRequested?.Invoke(this, new RequestConnectionEventArgs { ActionName = "TargetConnection", Control = (CdsMigratorPluginControl)Parent }); }
private void AcceptConnection(IAsyncResult ar) { UdpSocket client = null; bool succeed = false; AsyncState asyncState = ar.AsyncState as AsyncState; bool shoudContinue = asyncState.Socket.IsBound; if (!shoudContinue || !Listening) { return; } EndPoint senderIp = new IPEndPoint(IPAddress.Any, 0); try { int?count = asyncState.Socket?.EndReceiveFrom(ar, ref senderIp); var existing = csockets.Values.FirstOrDefault(p => p.RemoteEndPoint == senderIp); if (existing == null && count == 1) { succeed = CollectSocket(senderIp as IPEndPoint, out client); } else { Diagnostic.DiagnosticCenter.Instance.Log?.LogException(new ArgumentException(succeed ? "Unable to setup the client connection request." : "UDP Connection request should be one byte long")); } }catch (System.Net.Sockets.SocketException ex) { /* * Ignoring 10040, this exception happens often when client and server are on the same machine using the same IP address and port and this loop * receives data larger than the initial expected connection buffer size. * Also any incoming UDP package that is larger than the connection expected size will be ignored and discarded. */ if (ex.ErrorCode != 10040) { Diagnostic.DiagnosticCenter.Instance.Log?.LogException(ex); } } catch (ObjectDisposedException) { } catch (Exception ex) { Diagnostic.DiagnosticCenter.Instance.Log?.LogException(ex); } finally { byte[] dummy = new byte[1]; EndPoint endPoint = new IPEndPoint(_localEndpoint.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, Port); listener.BeginReceiveFrom(dummy, 0, dummy.Length, 0, ref endPoint, new AsyncCallback(AcceptConnection), new AsyncState() { Socket = listener }); } if (succeed) { OnConnectionRequested?.Invoke(client); } else { Diagnostic.DiagnosticCenter.Instance.Log?.LogException(new Exception(succeed ? "Unable to setup the client connection request." : "UDP Connection request should be one byte long")); } }