/// <summary> /// Sets up Socket ready to send data to endpoint as a client /// </summary> /// <param name="endPoint"></param> public void Connect(IEndPoint endPoint) { switch (_steamOptions.SteamMode) { case SteamModes.P2P: var steamEndPoint = (SteamEndpoint)endPoint; var steamIdentity = new SteamNetworkingIdentity(); steamIdentity.SetSteamID(steamEndPoint.Address); _steamSocketManager.HoHSteamNetConnection = SteamNetworkingSockets.ConnectP2P(ref steamIdentity, 0, 0, Array.Empty <SteamNetworkingConfigValue_t>()); _steamSocketManager.SteamConnections.Add(steamEndPoint, _steamSocketManager.HoHSteamNetConnection); break; case SteamModes.UDP: _endPoint = (SteamSocketFactory.SteamEndPointWrapper)endPoint; var address = new SteamNetworkingIPAddr(); address.SetIPv6(((IPEndPoint)_endPoint.inner).Address.GetAddressBytes(), (ushort)((IPEndPoint)_endPoint.inner).Port); _steamSocketManager.HoHSteamNetConnection = SteamNetworkingSockets.ConnectByIPAddress(ref address, 0, Array.Empty <SteamNetworkingConfigValue_t>()); _steamSocketManager.SteamConnections.Add(_endPoint, _steamSocketManager.HoHSteamNetConnection); break; default: Debug.LogWarning("Unknown steam mode. Please check if mode has been supported."); break; } }
public void Start(IEndPoint sourceEndPoint) { CurrentEndPoint = sourceEndPoint; UsedProtocol.Start(sourceEndPoint); reliableMessages.Clear(); receivedReliableMessages.Clear(); }
public static IEndPoint CreateSubstitute() { IEndPoint endpoint = Substitute.For <IEndPoint>(); endpoint.CreateCopy().Returns(endpoint); return(endpoint); }
public static IRail BuildRail(int id, IEndPoint endPointA, IEndPoint endPointB) { return(new Rail() { Id = id, EndPointA = endPointA, EndPointB = endPointB }); }
public StreamByteReceiver(IEndPoint remote, Stream client) { Remote = remote; this.client = client; Received = new MessageQueue<byte[]>(); Listen(); }
public void SendBaseMessage(BaseMessage message, IEndPoint endPoint) { if (message.MessageType.ShouldBeEncrypted()) { var client = realClient.ClientsById[message.RealDestinationId]; if (message.MessageType == MessageType.Data && realClient.ClientsById.ContainsKey(message.DestinationId)) { realClient.ClientsById[message.DestinationId].DataBytesSent += message.Payload.Length; } var key = client.MainKey; if (key == null) { realClient.MessageHandler.DisconnectClient(client.Id); throw new DnmpException($"Selected client key is null; Client Id: [{client.Id}]"); } message = new BaseMessage( SymmetricHelper.Encrypt(key, message.SecurityHash.Concat(message.Payload).ToArray()), message.MessageType, message.SourceId, message.DestinationId, message.RealSourceId, message.RealDestinationId, message.Guid, message.MessageFlags ); } if (realClient.ClientsById.ContainsKey(message.RealDestinationId)) { realClient.ClientsById[message.RealDestinationId].BytesSent += message.TotalLength; } SendRawBytes(message.GetBytes(), endPoint); }
public void SendReliableMessage(ITypedMessage typedMessage, ushort sourceId, ushort destinationId, ushort realDestinationId, IEndPoint to, MessageFlags messageFlags = MessageFlags.None) { try { if (!typedMessage.GetMessageType().IsReliable()) { throw new DnmpException("Message is not reliable"); } var id = Guid.NewGuid(); var message = new BaseMessage(typedMessage, sourceId, destinationId, realClient.SelfClient?.Id ?? 0xFFFF, realDestinationId, id, messageFlags); var messageInfo = new BaseMessagePair { Message = message, EndPoint = to }; reliableMessages.TryAdd(id, messageInfo); SendBaseMessage(message, to); EventQueue.AddEvent(ReliableCallback, new KeyValuePair <Guid, BaseMessagePair>(id, messageInfo), DateTime.Now.AddMilliseconds(500), id); } catch (Exception) { if (realClient.CurrentStatus == DnmpClient.ClientStatus.Disconnecting || realClient.CurrentStatus == DnmpClient.ClientStatus.NotConnected) { return; } throw; } }
public int Receive(byte[] buffer, out IEndPoint endPoint) { int c = socket.ReceiveFrom(buffer, ref Endpoint.inner); endPoint = Endpoint; return(c); }
public void Connect(IEndPoint endPoint) { Endpoint = (EndPointWrapper)endPoint; socket = CreateSocket(Endpoint.inner); socket.Connect(Endpoint.inner); }
private CoapObserveRelation ObserveAsync(Request request, Action <Response> notify, Action <FailReason> error) { IEndPoint endpoint = GetEffectiveEndpoint(request); CoapObserveRelation relation = new CoapObserveRelation(request, endpoint, _config); request.Respond += (o, e) => { Response resp = e.Response; lock (relation) { if (relation.Orderer.IsNew(resp)) { relation.Current = resp; Deliver(notify, e); } else { _Log.Debug(m => m("Dropping old notification: {0}", resp)); } } }; Action <FailReason> fail = r => { relation.Canceled = true; Fail(error, r); }; request.Rejected += (o, e) => fail(FailReason.Rejected); request.TimedOut += (o, e) => fail(FailReason.TimedOut); Prepare(request, endpoint).Send(); return(relation); }
/// <summary> /// Starts listens for data on an endpoint /// <para>Used by Server to allow clients to connect</para> /// </summary> /// <param name="endPoint">the endpoint to listen on</param> public void Bind(IEndPoint endPoint) { switch (_steamOptions.SteamMode) { case SteamModes.P2P: _steamSocketManager.Socket = SteamNetworkingSockets.CreateListenSocketP2P(0, 0, Array.Empty <SteamNetworkingConfigValue_t>()); break; case SteamModes.UDP: _endPoint = (SteamSocketFactory.SteamEndPointWrapper)endPoint; var address = new SteamNetworkingIPAddr(); address.SetIPv6(((IPEndPoint)_endPoint.inner).Address.GetAddressBytes(), (ushort)((IPEndPoint)_endPoint.inner).Port); _steamSocketManager.Socket = SteamNetworkingSockets.CreateListenSocketIP(ref address, 0, Array.Empty <SteamNetworkingConfigValue_t>()); break; default: _steamSocketManager.LogDebug("Unknown steam mode. Please check if mode has been supported.", LogType.Warning); throw new NotImplementedException("Unknown steam mode. This mode must not be implemented fully yet."); } }
public async Task StartAsFirstNodeAsync(IEndPoint sourceEndPoint, IEndPoint publicEndPoint, IAsymmetricKey key, ISymmetricKey dummySymmetricKey, byte[] selfCustomData) { if (CurrentStatus != ClientStatus.NotConnected) { return; } if (selfCustomData.Length > 65000) //TODO { throw new DnmpException("Custom data length is larger than 65000 bytes"); } SelfCustomData = selfCustomData; SelfClient = new DnmpNode { Id = 0, EndPoint = publicEndPoint, CustomData = SelfCustomData }; Initialize(sourceEndPoint, key, dummySymmetricKey); CurrentStatus = ClientStatus.Connected; logger.Info($"Started as first node on {sourceEndPoint} [{publicEndPoint}]"); OnClientConnected?.Invoke(SelfClient.Id); OnConnected?.Invoke(); MessageInterface.Initialize(SelfClient.Id); await Task.Delay(0); }
private void Initialize(IEndPoint sourceEndPoint, IAsymmetricKey key, ISymmetricKey dummySymmetricKey) { Key = key; DummySymmetricKey = dummySymmetricKey; MessageHandler.Start(); NetworkHandler.Start(sourceEndPoint); }
private void HandleNewConnection(IEndPoint endPoint, Packet packet) { // if invalid, then reject without reason if (!Validate(packet)) { return; } if (!_connectKeyValidator.Validate(packet.Buffer.array)) { RejectConnectionWithReason(endPoint, RejectReason.KeyInvalid); } else if (AtMaxConnections()) { RejectConnectionWithReason(endPoint, RejectReason.ServerFull); } // todo do other security stuff here: // - white/black list for endpoint? // (maybe a callback for developers to use?) else { AcceptNewConnection(endPoint); } }
public override void Start(IEndPoint listenEndPoint) { if (!(listenEndPoint is RealIPEndPoint)) { return; } var realEndPoint = ((RealIPEndPoint)listenEndPoint).RealEndPoint; socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(realEndPoint); socket.IOControl( (IOControlCode)(-1744830452), new byte[] { 0, 0, 0, 0 }, null ); socket.ReceiveBufferSize = receiveBufferSize; socket.SendBufferSize = sendBufferSize; var stateObject = new StateObject(receiveBufferSize) { EndPoint = new IPEndPoint(IPAddress.Any, 0) }; socket.BeginReceiveFrom(stateObject.Buffer, 0, stateObject.Buffer.Length, SocketFlags.None, ref stateObject.EndPoint, SocketReceiveCallback, stateObject); }
public HttpServices(IRawHttp http, ISession session, IEndPoint endPoint) { this.http = http; this.session = session; this.endPoint = endPoint; this.http.SetSession(session, endPoint); }
/// <summary> /// Sends the request over the specified endpoint. /// </summary> public Request Send(IEndPoint endpoint) { ValidateBeforeSending(); _endPoint = endpoint; endpoint.SendRequest(this); return(this); }
public async Task ConnectManyAsync(IEndPoint[] endPoints, IEndPoint sourceEndPoint, bool invokeEvents, IAsymmetricKey key, ISymmetricKey dummySymmetricKey, byte[] selfCustomData) { if (CurrentStatus != ClientStatus.NotConnected) { return; } if (selfCustomData.Length > 65000) { throw new DnmpException("Custom data length is larger than 65000 bytes"); } SelfCustomData = selfCustomData; Initialize(sourceEndPoint, key, dummySymmetricKey); CurrentStatus = ClientStatus.Connecting; if (invokeEvents) { connectionTimeoutEvent = EventQueue.AddEvent(_ => { NetworkHandler.Stop(); MessageHandler.Stop(); ClientsById.Clear(); CurrentStatus = ClientStatus.NotConnected; OnConnectionTimeout?.Invoke(); }, null, DateTime.Now.AddMilliseconds(Config.ConnectionTimeout)); } else { connectionTimeoutEvent = EventQueue.AddEvent(_ => { CurrentStatus = ClientStatus.NotConnected; }, null, DateTime.Now.AddMilliseconds(Config.ConnectionTimeout)); } logger.Debug($"Trying to connect to {endPoints.Length} endpoints. First: {endPoints.FirstOrDefault()}"); foreach (var endPoint in endPoints) { logger.Debug($"Trying to connect to {endPoint}"); try { NetworkHandler.SendBaseMessage( new BaseMessage(new ConnectionRequestMessage(key.GetNetworkId(), true), 0xFFFF, 0xFFFF), endPoint); } catch (Exception e) { logger.Warn($"Caught exception while trying to connect: {e.GetType().Name}('{e.Message}')"); } } if (invokeEvents) { return; } SpinWait.SpinUntil(() => CurrentStatus == ClientStatus.Connecting || CurrentStatus == ClientStatus.Handshaking); if (CurrentStatus == ClientStatus.NotConnected) { throw new TimeoutException("Connection timeout"); } await Task.Delay(0); }
/// <summary> /// Set properties on the request that are based on properties on this object /// </summary> /// <param name="request">Request we are going to send</param> /// <param name="endpoint">Endpoint to use sending the message</param> /// <returns>Request passed in</returns> protected Request Prepare(Request request, IEndPoint endpoint) { request.Type = _type; request.URI = Uri; request.OscoapContext = OscoapContext; if (UriPath != null) { request.UriPath = UriPath; } if (UriQuery != null) { request.UriQuery = UriQuery; } if (Blockwise != 0) { request.SetBlock2(BlockOption.EncodeSZX(Blockwise), false, 0); } if (endpoint != null) { request.EndPoint = endpoint; } return(request); }
void ISocket.Send(IEndPoint remoteEndPoint, byte[] packet, int length) { AddThisSocket(); if (!allSockets.TryGetValue(remoteEndPoint, out var other)) { // other socket might have been closed return; } // create copy because data is from buffer var clone = packet.Take(length).ToArray(); Sent.Add(new Packet { endPoint = remoteEndPoint, data = clone, length = length }); // mark as sent, but not as received if (StopAllMessages) { return; } other.received.Enqueue(new Packet { endPoint = endPoint, data = clone, length = length }); }
public void ConnectShouldReturnANewConnection() { IEndPoint endPoint = TestEndPoint.CreateSubstitute(); IConnection conn = peer.Connect(endPoint); Assert.That(conn, Is.TypeOf <Connection>(), "returned type should be connection"); Assert.That(conn.State, Is.EqualTo(ConnectionState.Connecting), "new connection should be connecting"); }
public int Receive(byte[] buffer, out IEndPoint endPoint) { int count = UDP.Receive(socket, ref receiveEndPoint.address, buffer, buffer.Length); endPoint = receiveEndPoint; return(count); }
public void BindShoudlCallSocketBind() { IEndPoint endPoint = TestEndPoint.CreateSubstitute(); peer.Bind(endPoint); socket.Received(1).Bind(Arg.Is(endPoint)); }
public RequestBuilder Connection(IServer server, IEndPoint endPoint, IPAddress address) { _Server = server; _Address = address; _EndPoint = endPoint; return(this); }
public ConnectionRequestConfirmReplyMessage(List <DnmpNode> clients, ushort newId, IEndPoint newEndPoint, IEndPointFactory endPointFactory, ISymmetricKey key) { Clients = clients; NewId = newId; NewEndPoint = newEndPoint; this.endPointFactory = endPointFactory; this.key = key; }
public void Bind(IEndPoint endPoint) { Endpoint = (EndPointWrapper)endPoint; socket = CreateSocket(Endpoint.inner); socket.DualMode = true; socket.Bind(Endpoint.inner); }
private (ISocket clientSocket, IEndPoint serverEndPoint) GetSocketAndEndPoint() { IEndPoint clientEndPoint = server.Players.First().Connection.EndPoint; TestSocket clientSocket = TestSocket.allSockets[clientEndPoint]; IEndPoint serverEndPoint = ((TestSocketFactory)server.SocketFactory).serverEndpoint; return(clientSocket, serverEndPoint); }
public RequestProcessServiceHost(IMessageBroker messageBroker, ILogger <RequestProcessServiceHost> logger) : base(messageBroker, logger) { _messageBroker = messageBroker; _logger = logger; this._rquestEndPoint = _messageBroker.GetServiceEndPoint <RequestMessage>(topicName: exchangename, topicType: ExchangeType.Direct, routingKey: "logs"); }
public void Bind(IEndPoint endPoint) { if (_active) { throw new InvalidOperationException("Peer is already active"); } _active = true; _socket.Bind(endPoint); }
public override void Send(byte[] data, IEndPoint endPoint) { if (!(endPoint is RealIPEndPoint)) { return; } socket.SendTo(data, ((RealIPEndPoint)endPoint).RealEndPoint); }
public CoapObserveRelation(Request request, IEndPoint endpoint, ICoapConfig config) { _config = config; _request = request; _endpoint = endpoint; _orderer = new ObserveNotificationOrderer(config); request.Reregistering += OnReregister; }
public IConnection Get(IEndPoint computer) { var conn = GetInternal(computer); if (conn != null) return conn; var added = new MissingEventArgs{EndPoint = computer}; ConnectionNotFound.FireEvent(this, added); if (added.Added) return GetInternal(computer); return conn; }
void GetNodesReply(RpcMail mail,IEndPoint ep, NodeId id, Dictionary<NodeId, List<IEndPoint>> nodes) { log.Info ("GetNodesReply", ep, id, nodes.Count); lock (nodeToMachine) { Add (ep, id); foreach (var kvp in nodes) foreach (var v in kvp.Value) Add (v, kvp.Key); } }
public void SetupServer() { Log.LogManager.Level = Log.LogLevel.Fatal; _config = new CoapConfig(); _config.DefaultBlockSize = 32; _config.MaxMessageSize = 32; CreateServer(); _clientEndpoint = new CoAPEndPoint(_config); _clientEndpoint.Start(); }
public void AddEndpoint(IEndPoint endpoint) { if(!string.IsNullOrEmpty(endpoint.EndpointConfiguration.ExchangeName)) { _endpointsByExchange[endpoint.EndpointConfiguration.ExchangeName] = endpoint; } if(!string.IsNullOrEmpty(endpoint.EndpointConfiguration.QueueName)) { _endpointsByQueue[endpoint.EndpointConfiguration.QueueName] = endpoint; } }
public void Add(IEndPoint machine, NodeId node) { lock(nodeToMachine) { if(!nodeToMachine.ContainsKey(node)) nodeToMachine[node] = new List<IEndPoint>(); if(!nodeToMachine[node].Contains(machine)) nodeToMachine[node].Add(machine); } NodeFound.FireEventAsync (machine, node); }
public static IEndPoint[] Get(IEndPoint ep) { var name = ep.ToString(); if (name == Environment.MachineName || name == "localhost" || name == "127.0.0.1") return new[] { Environment.MachineName, "localhost", "127.0.0.1" } .Select(n => new Cls.Connections.EndPoint(n)).ToArray(); var addresses = Dns.GetHostAddresses(name); return Enumerable.Repeat(ep, 1).Concat( addresses.Where(n => n.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) .Select(n => new Cls.Connections.EndPoint(n.ToString()))) .ToArray(); }
protected IChannelProxy ConfigureEndpoint(IEndPoint endpoint) { var channel = GetModel(); var configuration = endpoint.EndpointConfiguration; if (configuration.ExchangeName != null) BuildExchange(channel, configuration); if (configuration.QueueName != null) BuildQueue(channel, configuration); if (configuration.ExchangeName != null && configuration.QueueName != null) ForceBindQueue(channel, configuration); return new ChannelProxy(channel, _connectionManager.Protocol, configuration); }
protected IChannelProxy CreateProxy(IEndPoint endpoint) { IChannelProxy proxy = null; if (!endpoint.Initialized) { proxy = ConfigureEndpoint(endpoint); endpoint.Initialized = true; } else { proxy = new ChannelProxy(GetModel(), _connectionManager.Protocol, endpoint.EndpointConfiguration); } return proxy; }
public string DispatchAction(IEndPoint endpoint) { switch (endpoint.ActionName) { case "RegisterUser": return this.Tracker.RegisterUser(endpoint.Parameters["username"], endpoint.Parameters["password"], endpoint.Parameters["confirmPassword"]); case "LoginUser": return this.Tracker.LoginUser(endpoint.Parameters["username"], endpoint.Parameters["password"]); case "LogoutUser": return this.Tracker.LogoutUser(); case "CreateIssue": return this.Tracker.CreateIssue (endpoint.Parameters["title"], endpoint.Parameters["description"], (IssuePriority)System.Enum.Parse(typeof(IssuePriority), endpoint.Parameters["priority"], true), endpoint.Parameters["tags"].Split('|')); case "RemoveIssue": return this.Tracker.RemoveIssue(int.Parse(endpoint.Parameters["id"])); case "AddComment": var id = int.Parse(endpoint.Parameters["id"]); var text = endpoint.Parameters["text"]; return this.Tracker.AddComment(id, text); case "MyIssues": return this.Tracker.GetMyIssues(); case "MyComments": return this.Tracker.GetMyComments(); case "Search": return this.Tracker.SearchForIssues(endpoint.Parameters["tags"].Split('|')); default: return string.Format("Invalid action: {0}", endpoint.ActionName); } }
IConnection GetInternal(IEndPoint computer) { List<IConnection> c; lock (connections) foreach (var name in DnsAlias.Get(computer)) if (connections.TryGetValue(name, out c)) return c[0]; return null; }
public LocalSender(IEndPoint ep, LocalReceiver r) { Remote = ep; this.receiver = r; }
public void SetUp() { this._endPoint = MockRepository.GenerateMock<IEndPoint>(); this.dateTimeNow = MockRepository.GenerateMock<IDateTimeNow>(); }
/// <summary> /// Sends the request over the specified endpoint. /// </summary> public Request Send(IEndPoint endpoint) { ValidateBeforeSending(); _endPoint = endpoint; endpoint.SendRequest(this); return this; }
public LocalByteSender(IEndPoint remote, LocalByteReceiver receiver) { this.receiver = receiver; Remote = remote; }
private static IEndPoint GetDefaultEndPoint() { if (_default == null) { lock (typeof(EndPointManager)) { if (_default == null) { _default = CreateEndPoint(); } } } return _default; }
void GetNodes(RpcMail mail, IEndPoint ep) { log.Info("GetNodes " + ep); lock(nodeToMachine) Node.Reply(mail,ep, Node.Id, nodeToMachine.ToDictionary(n=>n.Key,n=>n.Value)); }
public CcTray(IEndPoint endPoint) { _endPoint = endPoint; }
public CcTray(IEndPoint endPoint, IDateTimeNow dateTimeNow) { this._endPoint = endPoint; this.dateTimeNow = dateTimeNow; }
internal CoapObserveRelation(Request request, IEndPoint endpoint) { _request = request; _endpoint = endpoint; }
public StreamByteSender(IEndPoint remote, Stream client) { this.Remote = remote; this.client = client; }
public void SetUp() { _endPoint = MockRepository.GenerateMock<IEndPoint>(); }
protected Request Prepare(Request request, IEndPoint endpoint) { request.Type = _type; request.URI = _uri; if (_blockwise != 0) request.SetBlock2(BlockOption.EncodeSZX(_blockwise), false, 0); if (endpoint != null) request.EndPoint = endpoint; return request; }
public async Task ConnectAsync(IEndPoint remoteEP) { SocketEndPoint socketEndPoint = remoteEP as SocketEndPoint; if (socketEndPoint == null) throw new ArgumentException("remoteEP must be of type SocketEndPoint", "remoteEP"); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { await Task.Factory.FromAsync(socket.BeginConnect(socketEndPoint.Address, socketEndPoint.Port, null, null), socket.EndConnect); } catch (SocketException ex) { throw new SocketConnectionException(ex); } catch (ObjectDisposedException) { throw new ObjectDisposedException(GetType().Name); } }
public LocalByteReceiver(IEndPoint remote) { Remote = remote; Received = new MessageQueue<byte[]>(); }
public LocalReceiver(IEndPoint ep) { Remote = ep; Received = new MessageQueue<object>(); }