protected override void ConnectionMade() { _client = new ConnectedClient(); _client.ServerId = _parent.ServerId; _client.ServerPublicName = _parent.ServerName; if (Connection is StreamSocketConnection) { _client.IPAddress = (Connection as StreamSocketConnection).RemoteEndPoint.Address.ToString(); _client.Port = (Connection as StreamSocketConnection).RemoteEndPoint.Port; } using (IdentificationMessage message = new IdentificationMessage()) { AddValueToMessage(message, _client); SendMessage(message); } base.ConnectionMade(); if (ClientConnected != null) { ClientConnected(this, new IdentificationEventArgs(_client)); } }
private async void ProcessClientAsync(TcpClient client) { var connectedClient = new ConnectedClient(); try { connectedClient.TcpClient = client; connectedClient.Stream = client.GetStream(); connectedClient.MessageStream = new MemoryStream(); connectedClient.Buffer = new byte[64]; _clients.Add(connectedClient); } catch (Exception e) { Console.WriteLine("Error while connecting " + e.Message); } try { await ReadAndBroadcast(connectedClient); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } }
public async Task ProcessOutgoingDataAsync(ConnectedClient _client) { var client = _client.Client; while (true) { var stream = client.GetStream(); // byte[] length = new byte[4]; // await stream.ReadAsync(length,0,4); // int count = BitConverter.ToInt32(length,0); // //stream.Read(buffer,0,count); //Packet[] newpackets = Packet.ArrayFromBytes(buffer); //JunctionedData.AddRange(newpackets.ToList()); //Console.WriteLine(BitConverter.ToInt32(newpackets[0].data,0)+" "+newpackets.Length); if (_client.ToClientData.Count > 0) { var outgoing = Packet.ArrayToBytes(_client.ToClientData.ToArray()); // JunctionedData.AddRange(_client.OutgoingData); _client.ToClientData.Clear(); //stream.Flush(); SendData(outgoing, client); } } }
public async Task StartAcceptingConnectionsAsync(){ while(true){ var _client = await _server.AcceptTcpClientAsync(); Console.WriteLine("CLIENT CONNECTED"); var conclient = new ConnectedClient(_client); _clients.Add(conclient); Task.Run(()=>{ProcessDataAsync(conclient);}); } }
private async Task ReadAndBroadcast(ConnectedClient connectedClient, int offset = 0) { int read = await connectedClient.Stream.ReadAsync(connectedClient.Buffer, offset, connectedClient.Buffer.Length - offset); if (read == 0) return; connectedClient.MessageStream.Write(connectedClient.Buffer, 0, 5); var length = CodedInputStream.CreateInstance(connectedClient.Buffer, 0, 5).ReadRawVarint32(); var lengthSize = CodedOutputStream.ComputeRawVarint32Size(length); int readLeft = (int) (length - 5 + lengthSize); var count = Math.Min(read - 5, readLeft); await connectedClient.MessageStream.WriteAsync(connectedClient.Buffer, 5, count); if (readLeft > read - 5) { readLeft -= count; await ReadWhatLeft(connectedClient, readLeft); await ReadAndBroadcast(connectedClient); } else { int currentOffset = count + 5; while (currentOffset < read - 4) { var messageSize = CodedInputStream.CreateInstance(connectedClient.Buffer, currentOffset, 5).ReadRawVarint32(); var intSize = CodedOutputStream.ComputeRawVarint32Size(messageSize); int left = (int) (messageSize - 5 + intSize); var bufferLeft = read - currentOffset - 5; if (left < bufferLeft) { await connectedClient.MessageStream.WriteAsync(connectedClient.Buffer, currentOffset + 5, left); currentOffset += 5 + left; } else { await connectedClient.MessageStream.WriteAsync(connectedClient.Buffer, currentOffset + 5, bufferLeft); left -= bufferLeft; await ReadWhatLeft(connectedClient, left); await ReadAndBroadcast(connectedClient); return; } } BroadcastMessage(connectedClient); int nextOffset = read - currentOffset; for (int i = 0; i < nextOffset; ++i) { connectedClient.Buffer[i] = connectedClient.Buffer[i + currentOffset]; } await ReadAndBroadcast(connectedClient, nextOffset); } }
public ConnectedClient AddClient(IPEndPoint connection, string fingerprint) { ConnectedClient c = clients.Where(x => x.HardwareID == fingerprint).SingleOrDefault(); if (c == null) { c = new ConnectedClient() { HardwareID = fingerprint, ClientID = GenerateID(), Connection = connection, }; clients.Add(c); } if(connections.Contains(connection)) connections.Remove(connection); return c; }
public void Register() { var client = CurrentClient; lock (_clients) { if (_clients.ContainsKey(client.ClientId)) { throw new NDistException("Client has already registered. Register method must be called only once."); } var monitor = new ConnectedClient(client); monitor.Client.Disconnected += Client_Disconnected; _clients[client.ClientId] = monitor; } Console.WriteLine("Registered a new client: " + client.ClientId); }
internal void DeleteFile(string virtualPath) { ConnectedClient.DeleteFile(virtualPath); }
public ValueTask HandleAsync(ConnectedClient sender, Disconnect message, CancellationToken cancellationToken) { _store.Remove(sender.ClientId); return(sender.Connection.SendAsync(new Disconnected("Requested."), cancellationToken)); }
private void ServerOnClientConnected(object sender, ConnectedClient e) { logger.Debug("Hurra ein neuer Spieler"); e.ServerSubscription = e.Subscribe(this); e.NetworkChannelSubscription = UpdateHub.Subscribe(e, DefaultChannels.Network); }
/// <summary> /// Gets the client tag or creates it if necessary. /// </summary> protected ClientTag GetClientTag(ConnectedClient client) { return(client.Tag as ClientTag ?? throw new InvalidOperationException("Client tag must not be null.")); }
/// <summary> /// Performs actions when initializing the connected client. /// </summary> protected override void OnClientInit(ConnectedClient client) { client.Tag = new ClientTag(); }
/// <summary> /// Gets the events. /// </summary> protected void GetEvents(ConnectedClient client, DataPacket request) { byte[] buffer = request.Buffer; int index = ArgumentIndex; TimeRange timeRange = GetTimeRange(buffer, ref index); long dataFilterID = GetInt64(buffer, ref index); DataFilter dataFilter = null; if (dataFilterID > 0) { dataFilter = serverCache.DataFilterCache.Get(dataFilterID); if (dataFilter == null) { dataFilterID = 0; } } else { bool useCache = GetBool(buffer, ref index); dataFilter = GetDataFilter(typeof(Event), buffer, ref index); if (useCache) { dataFilterID = serverCache.GetNextID(); serverCache.DataFilterCache.Add(dataFilterID, dataFilter); } } int archiveBit = GetByte(buffer, ref index); List <Event> events = dataFilter == null ? new List <Event>() : archiveHolder.GetEvents(timeRange, dataFilter, archiveBit); int totalEventCount = events.Count; int blockCount = totalEventCount > 0 ? (int)Math.Ceiling((double)totalEventCount / EventBlockCapacity) : 1; int eventIndex = 0; buffer = client.OutBuf; for (int blockNumber = 1; blockNumber <= blockCount; blockNumber++) { ResponsePacket response = new ResponsePacket(request, buffer); index = ArgumentIndex; CopyInt32(blockNumber, buffer, ref index); CopyInt32(blockCount, buffer, ref index); CopyInt64(dataFilterID, buffer, ref index); CopyInt32(totalEventCount, buffer, ref index); int eventCount = Math.Min(totalEventCount - eventIndex, EventBlockCapacity); // events in this block CopyInt32(eventCount, buffer, ref index); for (int i = 0; i < eventCount; i++) { CopyEvent(events[eventIndex], buffer, ref index); eventIndex++; } response.BufferLength = index; client.SendResponse(response); } }
private void OnClientConnection(IAsyncResult asyn) { if (m_Closed) { return; } try { Socket clientSocket = m_socket.EndAccept(asyn); ConnectedClient connectedClient = new ConnectedClient(clientSocket); RaiseClientConnected(clientSocket); connectedClient.MessageRecived += OnMessageRecived; connectedClient.Disconnected += OnClientDisconnection; connectedClient.StartListen(); long key = clientSocket.Handle.ToInt64(); if (m_clients.ContainsKey(key)) { Debug.Fail(string.Format( "Client with handle key '{0}' already exist!", key)); } m_clients[key] = connectedClient; m_socket.BeginAccept(new AsyncCallback(OnClientConnection), null); } catch (ObjectDisposedException odex) { Debug.Fail(odex.ToString(), "OnClientConnection: Socket has been closed"); } catch (Exception sex) { Debug.Fail(sex.ToString(), "OnClientConnection: Socket failed"); } }
public MessageArrivedArgs(string message, int num, ConnectedClient cl) { this.message = message; this.num = num; this.cl = cl; }
void Poslusanje() { listener.Start(); while (!stopped) { if ((paused) || (client_num >= maxClients)) Thread.Sleep(30); TcpClient client = listener.AcceptTcpClient(); ClientConnectedArgs cca = new ClientConnectedArgs(client_num); ClientConnected(this, cca); client_num++; ConnectedClient cl = new ConnectedClient(client); clients.Add(cl); accepted = false; Thread thr = new Thread(Poslusaj); thr.IsBackground = true; thr.Start(); while (!accepted) Thread.Sleep(5); } }
/// <summary> /// Sends data to a client /// </summary> /// <param name="cl">Client</param> /// <param name="Message">Message string</param> public void SendToClient(ConnectedClient cl, string Message) { try { cl.writer.Write(Message); } catch { StopClient(cl); } }
/// <summary> /// Disconects the given client /// </summary> /// <param name="cl">Client</param> public void StopClient(ConnectedClient cl) { try { cl.client.Close(); } catch { } try { ConnectionClosedArgs cca = new ConnectionClosedArgs(cl); ConnectionClosed(this, cca); } catch { } }
public Task OnClientConnected(ConnectedClient client) { //_logger.LogInformation("OnClientConnected: {clientId}", client.ClientId); return(Task.CompletedTask); }
public override void Handle(ConnectedClient sender, CastSkillCommand message) { _battleApp.Cast(sender.PlayerId, message.SkillId, new[] { message.TargetId }); }
internal IEnumerable <SftpFile> GetContents(string virtualPath) { return(ConnectedClient.ListDirectory(virtualPath)); }
internal void CreateDirectoryInternal(string virtualPath) { ConnectedClient.CreateDirectory(virtualPath); }
public ConnectionClosedArgs(ConnectedClient cl) { this.cl = cl; }
private void DisconnectClient(ConnectedClient connection) { connectedClients.Remove(connection); }
internal void HandleIdentificationRequest(IMessage receivedMessage) { _identification = (receivedMessage as IdentificationMessage).Client; using (IdentificationMessage message = new IdentificationMessage()) { _identification.PublicName = _clientName; ClientProtocol.AddValueToMessage(message, _identification); ClientProtocol.SendMessage(message); if (ProtocolMadeConnection != null) { ProtocolMadeConnection(this, EventArgs.Empty); } } }
/// <summary> /// Processes the incoming request. /// </summary> protected override void ProcessCustomRequest(ConnectedClient client, DataPacket request, out ResponsePacket response, out bool handled) { response = null; handled = true; switch (request.FunctionID) { case FunctionID.GetCurrentData: GetCurrentData(client, request, out response); break; case FunctionID.GetTrends: GetTrends(client, request); break; case FunctionID.GetTimestamps: GetTimestamps(client, request, out response); break; case FunctionID.GetSlice: GetSlice(client, request, out response); break; case FunctionID.GetLastWriteTime: GetLastWriteTime(client, request, out response); break; case FunctionID.WriteCurrentData: WriteCurrentData(client, request, out response); break; case FunctionID.WriteHistoricalData: WriteHistoricalData(client, request, out response); break; case FunctionID.GetEventByID: GetEventByID(client, request, out response); break; case FunctionID.GetEvents: GetEvents(client, request); break; case FunctionID.WriteEvent: WriteEvent(client, request, out response); break; case FunctionID.AckEvent: AckEvent(client, request, out response); break; case FunctionID.SendCommand: SendCommand(client, request, out response); break; case FunctionID.GetCommand: GetCommand(client, request, out response); break; case FunctionID.DisableGettingCommands: DisableGettingCommands(client, request, out response); break; default: handled = false; break; } }
private static void StatusServerOnClientConnected(object sender, ConnectedClient connectedClient) { }
/// <summary> /// Gets the role name of the connected client. /// </summary> protected override string GetRoleName(ConnectedClient client) { Role role = client == null ? null : coreLogic.BaseDataSet.RoleTable.GetItem(client.RoleID); return(role == null ? "" : role.Name); }
private static void ServerOnClientDisconnected(object sender, ConnectedClient tcpClient) { Program.Log($"Client disconnected: {tcpClient.Client.Client.Handle}"); }
public ClientAlreadyConnectedException(ConnectedClient connectedClient) : base($"Client {connectedClient.ClientId} is already connected.") { }
private static void ServerOnClientConnected(object sender, ConnectedClient tcpClient) { Program.Log( $"Client connected: {tcpClient.Client.Client.Handle} - {((IPEndPoint) tcpClient.Client.Client.RemoteEndPoint).Address}"); }
public DataReceiver(ConnectedClient client) { _client = client; RegisterIntoPipeline(); }
private void Handler_EndSession(ConnectedClient <T> Client) { EventEndSession?.Invoke(); }
internal Stream CreateFileInternal(string virtualPath) { return(ConnectedClient.Create(virtualPath)); }
IController <T> IController <T> .GetNewControler(ConnectedClient <T> client) { return(this); }
internal SftpFile GetSftpFile(string virtualPath) { return(ConnectedClient.Get(virtualPath)); }
internal void NotifyClientDisconnected(Server.ServerListener listener, ConnectedClient disconnectedClient) { ClientDisconnected?.Invoke(this, disconnectedClient); }
internal void DeleteDirectory(string virtualPath) { ConnectedClient.DeleteDirectory(virtualPath); }
private void AcceptCallback(Socket socket, SocketAsyncEventArgs socketAsyncEventArgs) { // Check for error if (socketAsyncEventArgs.SocketError != SocketError.Success) { HandleCommunicationError(socket, new Exception("Accept failed, error = " + socketAsyncEventArgs.SocketError)); } var handler = socketAsyncEventArgs.AcceptSocket; socketAsyncEventArgs.AcceptSocket = null; // Post accept on the listening socket if (!TryUnsafeSocketOperation(socket, SocketAsyncOperation.Accept, socketAsyncEventArgs)) { throw new Exception("Socket accept failed"); } try { // Turn on or off Nagle algorithm handler.NoDelay = !_useNagleAlgorithm; // Set the linger state handler.LingerState = _lingerOption; } catch (SocketException ex) { HandleCommunicationError(handler, ex); return; } catch (ObjectDisposedException) { // If disposed, handle communication error was already done and we're just catching up on other threads. suppress it. return; } // If we are at max clients, disconnect if (!_maxConnectionsSemaphore.WaitOne(1000)) { handler.Close(); return; } // Enroll in currently connected client sockets var connectedClient = new ConnectedClient(handler); _currentlyConnectedClientsLock.EnterWriteLock(); try { _currentlyConnectedClients.Add(connectedClient); } finally { _currentlyConnectedClientsLock.ExitWriteLock(); } // Fire the event if needed var clientConnected = ClientConnected; if (clientConnected != null) { // Fire the event clientConnected(this, EventArgs.Empty); } // Create receive buffer queue for this client _currentlyConnectedClientsReceiveQueuesLock.EnterWriteLock(); try { _currentlyConnectedClientsReceiveQueues.Add(handler, new BlockingQueue<SocketAsyncEventArgs>(_maximumConnections * 10)); } finally { _currentlyConnectedClientsReceiveQueuesLock.ExitWriteLock(); } if (!TryUnsafeSocketOperation(handler, SocketAsyncOperation.Receive, _socketAsyncEventArgsReceivePool.Pop())) { return; } ProcessReceivedMessage(connectedClient); }
internal void NotifyClientConnected(Server.ServerListener listener, ConnectedClient newClient) { ClientConnected?.Invoke(this, newClient); }
private async void BroadcastMessage(ConnectedClient connectedClient) { foreach (var client in _clients.Where(client => client != connectedClient)) { await connectedClient.Stream.WriteAsync(connectedClient.MessageStream.GetBuffer(), 0, (int) connectedClient.MessageStream.Length); } connectedClient.MessageStream.SetLength(0); }
public void ShouldContainClientIdInMessage( [Frozen] ConnectedClient client, ClientAlreadyConnectedException sut) { Assert.Contains(client.ClientId, sut.Message); }
public List <ConnectedPlayer> getClientPlayers(ConnectedClient c) { return(players.FindAll(x => x.client.peerID == c.peerID)); }
private void HandleIdentificationMessage(IMessage message) { if (message is IdentificationMessage) { _client = (message as IdentificationMessage).Client; if (ClientIdentified != null) { ClientIdentified(this, new IdentificationEventArgs(_client)); } SendFullFileList(); } else throw new InvalidOperationException(); }
public DataTransferHandler(Connection connection, ConnectedClient connectedClient) : base(connection, connectedClient) { }
public CommandHandler(Connection connection, ConnectedClient connectedClient) : base(connection, connectedClient) { }
public UserConnected(ConnectedClient client) { Client = client; }
private void ProcessReceivedMessage(ConnectedClient connectedClient) { int bytesToRead = -1; int threadId = -1; int availableTest = 0; int controlBytesOffset = 0; byte[] protocolBuffer = new byte[_controlBytesPlaceholder.Length]; byte[] resultBuffer = null; var handler = connectedClient.Socket; BlockingQueue<SocketAsyncEventArgs> receiveBufferQueue = null; _currentlyConnectedClientsReceiveQueuesLock.EnterReadLock(); try { if (!_currentlyConnectedClientsReceiveQueues.TryGetValue(handler, out receiveBufferQueue)) { // Peace out! return; } } finally { _currentlyConnectedClientsReceiveQueuesLock.ExitReadLock(); } // Loop until socket is done while (_isListening) { // If the socket is disposed, we're done try { availableTest = handler.Available; } catch (ObjectDisposedException) { // Peace out! return; } // Get the next buffer from the queue var socketAsyncEventArgs = receiveBufferQueue.Dequeue(); if (socketAsyncEventArgs == null) { continue; } var buffer = socketAsyncEventArgs.Buffer; int bytesRead = socketAsyncEventArgs.BytesTransferred; int currentOffset = 0; while (currentOffset < bytesRead) { // Check if we need to get our control byte values if (bytesToRead == -1) { var controlBytesNeeded = _controlBytesPlaceholder.Length - controlBytesOffset; var controlBytesAvailable = bytesRead - currentOffset; var controlBytesToCopy = Math.Min(controlBytesNeeded, controlBytesAvailable); // Copy bytes to control buffer Buffer.BlockCopy(buffer, currentOffset, protocolBuffer, controlBytesOffset, controlBytesToCopy); controlBytesOffset += controlBytesToCopy; currentOffset += controlBytesToCopy; // Check if done if (controlBytesOffset == _controlBytesPlaceholder.Length) { // Parse out control bytes ExtractControlBytes(protocolBuffer, out bytesToRead, out threadId); // Reset control bytes offset controlBytesOffset = 0; // Ensure message is not larger than maximum message size if (bytesToRead > _maxMessageSize) { HandleCommunicationError(handler, new InvalidOperationException(string.Format("message of length {0} exceeds maximum message length of {1}", bytesToRead, _maxMessageSize))); return; } } // Continue the loop continue; } // Have control bytes, get message bytes // SPECIAL CASE: if empty message, skip a bunch of stuff if (bytesToRead != 0) { // Initialize buffer if needed if (resultBuffer == null) { resultBuffer = new byte[bytesToRead]; } var bytesAvailable = bytesRead - currentOffset; var bytesToCopy = Math.Min(bytesToRead, bytesAvailable); // Copy bytes to buffer Buffer.BlockCopy(buffer, currentOffset, resultBuffer, resultBuffer.Length - bytesToRead, bytesToCopy); currentOffset += bytesToCopy; bytesToRead -= bytesToCopy; } // Check if we're done if (bytesToRead == 0) { if (resultBuffer != null) { // Done, add to complete received messages CompleteMessage(handler, threadId, resultBuffer); // Reset message state resultBuffer = null; } bytesToRead = -1; threadId = -1; connectedClient.LastResponse = DateTime.UtcNow; } } // Push the buffer back onto the pool _socketAsyncEventArgsReceivePool.Push(socketAsyncEventArgs); } }
private async Task ReadWhatLeft(ConnectedClient connectedClient, int readLeft) { while (readLeft > 0) { int res = await connectedClient.Stream.ReadAsync(connectedClient.Buffer, 0, Math.Min(connectedClient.Buffer.Length, readLeft)); await connectedClient.MessageStream.WriteAsync(connectedClient.Buffer, 0, res); readLeft -= res; } var message = Message.ParseDelimitedFrom(new MemoryStream(connectedClient.MessageStream.GetBuffer(), 0, (int) connectedClient.MessageStream.Length)); BroadcastMessage(connectedClient); }