void CloseConnection(SocketConnection sc) { lock (synclock) connections.Remove(sc); sc.Close(); }
public void Shutdown() { if (_task == null) { return; } try { _cancellationTokenSource.Cancel(); _task.Wait(); } catch (AggregateException aex) { aex.Handle(ex => { if (!(ex is TaskCanceledException)) { return(false); } _errorHandler.HandleError("Exception occurred when stopping agent controller.", ex); return(true); }); } finally { _socketConnection.Close(); } }
public T Send(string ip, int port, int timeout) { var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var sc = new SocketConnection(client); try { client.Connect(new IPEndPoint(IPAddress.Parse(ip), port)); if (sc.Socket.Connected) { // Send request to AppServer var data = PrepareRequestBuffer(); sc.Socket.Send(data, 0, data.Length, SocketFlags.None); int bytesReceived = sc.Socket.Receive(sc.SocketBuffer, 0, sc.BufferSize, SocketFlags.None); while (bytesReceived > 0) { // There might be more data, so store the data received so far and check for eof if (sc.CopyBuffer(bytesReceived)) { // All the data has arrived. break; } else { bytesReceived = sc.Socket.Receive(sc.SocketBuffer, 0, sc.BufferSize, SocketFlags.None); } } return(BuildResponse(sc)); } else { throw new ApplicationException("Socket was not connected"); } } catch (Exception ex) { Logger.Error("An error has occured while trying to connect to the AppServer. Exception = {0}", LogSource.AppServer, ex); throw new ClientException("An error has occured", ex); } finally { try { sc.Close(); } catch { } try { if (sc.Socket.Connected) { sc.Socket.Shutdown(SocketShutdown.Both); } } catch { } } }
void CloseConnection(SocketConnection sc) { lock (synclock) connections.Remove(sc); sc.Close(); }
// 销毁 public void Dispose() { _instance = null; if (null != _conn) { _conn.Close(); } }
public void Close() { // Setup SocketConnection connection = new SocketConnection(_mockSocket.Object); // Act connection.Close(); _receiveCallback?.Invoke(_mockResult.Object); // Verify _mockSocket.Verify(s => s.EndReceive(It.IsAny <IAsyncResult>()), Times.Never()); }
public void SendAfterClosed() { // Setup SocketConnection connection = new SocketConnection(_mockSocket.Object); // Act connection.Close(); bool success = connection.SendMessage(new byte[] { 0x01, 0x02 }); // Verify Assert.False(success); }
/// <inheritdoc /> protected override async Task <CallResult <bool> > SubscribeAndWait(SocketConnection socket, object request, SocketSubscription subscription) { var btRequest = (ConnectionRequest)request; if (btRequest.RequestName != null) { var subResult = await((ISignalRSocket)socket.Socket).InvokeProxy <bool>(btRequest.RequestName, btRequest.Parameters).ConfigureAwait(false); if (!subResult.Success || !subResult.Data) { _ = socket.Close(subscription); return(new CallResult <bool>(false, subResult.Error ?? new ServerError("Subscribe returned false"))); } } subscription.Confirmed = true; return(new CallResult <bool>(true, null)); }
private bool Start() { try { for (var i = 0; i < _numSenders; i++) { var socket = _socketFactory.Connect(); if (socket == null) { _errorHandler.HandleError($"Failed to open HQ Data connection to host {_socketFactory.Host} on port {_socketFactory.Port} with a retry of {_socketFactory.RetryDurationInMilliseconds} millisecond(s)."); return(false); } var socketConnection = new SocketConnection(socket); try { _dataConnectionHandshake.PerformHandshake(_runId, socketConnection); } catch (HandshakeException ex) { socketConnection.Close(); _errorHandler.HandleError("Unable to perform data connection handshake.", ex); return(false); } _connections.Add(socketConnection); _senders.Add(new PooledMessageSender(_bufferPool, socketConnection.OutputWriter, _errorHandler, _logger)); } } catch (Exception ex) { _errorHandler.HandleError("Failed to start the MessageSenderManager.", ex); return(false); } return(true); }
public void SendDisconnected() { // Setup SocketConnection connection = new SocketConnection(_mockSocket.Object); List <byte> sent = new List <byte>(); _mockSocket.Setup(s => s.SendAsync(It.IsAny <byte[]>(), It.IsAny <SendCallbackDelegate>())).Callback <byte[], SendCallbackDelegate>((buffer, callback) => { connection.Close(); callback.Invoke(SocketError.Success, 0); }); // Act connection.SendMessage(new byte[] { 0x01, 0x02 }); connection.SendComplete.WaitOne(2000); // Verify - SendAsync should be called only once before the connection is closed and the sending process stops. _mockSocket.Verify(s => s.SendAsync(It.IsAny <byte[]>(), It.IsAny <SendCallbackDelegate>()), Times.Once()); }
public void Run() { try { var reader = new AGIReader(socket); var writer = new AGIWriter(socket); AGIRequest request; using (var enlarger = new SocketConnectionTimeoutEnlarger(socket, 500)) request = reader.ReadRequest(); //Added check for when the request is empty //eg. telnet to the service if (request.Request.Count > 0) { var channel = new AGIChannel(writer, reader, _SC511_CAUSES_EXCEPTION, _SCHANGUP_CAUSES_EXCEPTION); AGIScript script = mappingStrategy.DetermineScript(request); Thread.SetData(_channel, channel); if (script != null) { #if LOGGER logger.Info("Begin AGIScript " + script.GetType().FullName + " on " + Thread.CurrentThread.Name); #endif script.Service(request, channel); #if LOGGER logger.Info("End AGIScript " + script.GetType().FullName + " on " + Thread.CurrentThread.Name); #endif } else { var error = "No script configured for URL '" + request.RequestURL + "' (script '" + request.Script + "')"; channel.SendCommand(new VerboseCommand(error, 1)); #if LOGGER logger.Error(error); #endif } } else { var error = "A connection was made with no requests"; #if LOGGER logger.Error(error); #endif } } catch (AGIHangupException) { } catch (IOException) { } catch (AGIException ex) { #if LOGGER logger.Error("AGIException while handling request", ex); #else throw ex; #endif } catch (Exception ex) { #if LOGGER logger.Error("Unexpected Exception while handling request", ex); #else throw ex; #endif } Thread.SetData(_channel, null); try { socket.Close(); } #if LOGGER catch (IOException ex) { logger.Error("Error on close socket", ex); } #else catch { } #endif }
private void NewConnections() { // todo: would accept new connections from clients and things. TcpClient clientSocket = new TcpClient(); while (Listening) { try { clientSocket = ServerListener.AcceptTcpClient(); Byte[] bytesFrom = new Byte[clientSocket.ReceiveBufferSize]; string dataFromClient; NetworkStream netStream = clientSocket.GetStream(); try { netStream.Read(bytesFrom, 0, Convert.ToInt32(clientSocket.ReceiveBufferSize)); } catch (Exception ex) { Logging.Log("NewConRead", ex); continue; } dataFromClient = Encoding.UTF8.GetString(bytesFrom).Trim().Replace("\0", ""); IPEndPoint ipEnd = clientSocket.Client.RemoteEndPoint as IPEndPoint; if (string.IsNullOrWhiteSpace(dataFromClient)) { clientSocket.Close(); continue; } dataFromClient = dataFromClient.Substring(1, dataFromClient.LastIndexOf("`") - 1); SocketConnection user = null; try { string adminAcc = ""; if (dataFromClient.Contains("#")) { // attempting to vote on behalf of another user. string[] split = dataFromClient.Split('#'); dataFromClient = split[1]; adminAcc = split[0]; } user = new SocketConnection(clientSocket, dataFromClient.ToLower()); if (Program.TryGetUser(adminAcc, out User admin)) { user.AdminBehalfOf = admin; } }catch (ArgumentException ex) { // user not found SocketConnection.WriteConnection(clientSocket, "UnknownUser"); Logging.Log("UnknUser", ex); continue; } catch (Exception ex) { Logging.Log("NewSock", ex); continue; } // as soon as we get a connection, we should disable the ability to edit user info from UI if (!Program.Options.Allow_Modifications_When_Voting) { Program.ServerUIForm.PermittedStudentEdits(ServerUI.UIForm.EditCapabilities.None); } lock (LockClient) { if (CurrentClients.Select(x => x.UserName).Contains(dataFromClient) || ClientQueue.Select(x => x.UserName).Contains(dataFromClient)) { if (!Program.Options.Simultaneous_Session_Allowed) { user.Send("REJECT:Already"); user.Close("Already Connected"); } else { // considering we shouldnt have a person connected multiple times, this shouldnt really be called anyway user.UserName += rnd.Next(0, 999).ToString("000"); // technically possible for this to collide.. but unlikely } } } user.IPAddress = ipEnd.Address.ToString(); Logging.Log(Logging.LogSeverity.Warning, "New connection: " + ipEnd.Address.ToString() + " -> " + user.User.ToString(), "NewCon"); if (Program.Database.AlreadyVotedNames.Contains(user.User.AccountName)) { Logging.Log(Logging.LogSeverity.Warning, "Refusing connection: " + user.User.ToString() + ", already voted."); user.Send("REJECT:Voted"); user.Close("Prior Vote"); continue; } if (user.AdminBehalfOf != null) { Logging.Log(Logging.LogSeverity.Warning, $"{user.AdminBehalfOf.AccountName} is voting on the behalf of user {user.User.AccountName}", "NewCon"); if (!user.AdminBehalfOf.Flags.Contains(Flags.System_Operator)) { user.Send($"REJECT:No-behalf"); user.Close("No permissions to vote on behalf of another"); continue; } } if (user.User.Flags.Contains(Flags.Disallow_Vote_Staff)) { user.Send("REJECT:Blocked-Online"); user.Close("Blocked from voting, online-only account"); continue; } var getKick = GetKick(user); if (getKick != null) { user.Send("REJECT:Kicked:" + getKick.Reason); user.Close("prior kicked, by " + getKick.Admin.AccountName); continue; } lock (LockClient) { ClientQueue.Add(user); user.Send("QUEUE:" + ClientQueue.Count); while (CurrentClients.Count < Program.Options.Maximum_Concurrent_Connections) { if (ClientQueue.Count == 0) { break; } ClientQueue[0].AcceptFromQueue(); CurrentClients.Add(ClientQueue[0]); ClientQueue.RemoveAt(0); } var adminsInQueue = ClientQueue.Where(x => x.Authentication > Authentication.Student).ToList(); foreach (var adm in adminsInQueue) { ClientQueue.RemoveAll(x => x.UserName == adm.UserName); CurrentClients.Add(adm); adm.AcceptFromQueue(true); } } } catch (Exception ex) { Logging.Log("NewConn", ex); } } }
/// <summary> /// Reads line by line from the asterisk server, sets the protocol identifier as soon as it is /// received and dispatches the received events and responses via the associated dispatcher. /// </summary> /// <seealso cref="ManagerConnection.DispatchEvent(ManagerEvent)" /> /// <seealso cref="ManagerConnection.DispatchResponse(Response.ManagerResponse)" /> /// <seealso cref="ManagerConnection.setProtocolIdentifier(String)" /> internal void Run() { if (mrSocket == null) { throw new SystemException("Unable to run: socket is null."); } string line; while (true) { try { while (!die) { #region check line from * if (!is_logoff) { if (mrSocket != null && mrSocket.Initial) { Reinitialize(); } else if (disconnect) { disconnect = false; mrConnector.DispatchEvent(new DisconnectEvent(mrConnector)); } } if (lineQueue.Count == 0) { if (lastPacketTime.AddMilliseconds(mrConnector.PingInterval) < DateTime.Now && mrConnector.PingInterval > 0 && mrSocket != null && !wait4identiier && !is_logoff ) { if (pingHandler != null) { if (pingHandler.Response == null) { // If one PingInterval from Ping without Pong then send Disconnect event mrConnector.RemoveResponseHandler(pingHandler); mrConnector.DispatchEvent(new DisconnectEvent(mrConnector)); } pingHandler.Free(); pingHandler = null; } else { // Send PING to * try { pingHandler = new ResponseHandler(new PingAction(), null); mrConnector.SendAction(pingHandler.Action, pingHandler); } catch { disconnect = true; mrSocket = null; } } lastPacketTime = DateTime.Now; } Thread.Sleep(50); continue; } #endregion lastPacketTime = DateTime.Now; lock (((ICollection)lineQueue).SyncRoot) line = lineQueue.Dequeue().Trim(); #if LOGGER logger.Debug(line); #endif #region processing Response: Follows if (processingCommandResult) { string lineLower = line.ToLower(Helper.CultureInfo); if (lineLower == "--end command--") { var commandResponse = new CommandResponse(); Helper.SetAttributes(commandResponse, packet); commandList.Add(line); commandResponse.Result = commandList; processingCommandResult = false; packet.Clear(); mrConnector.DispatchResponse(commandResponse); } else if (lineLower.StartsWith("privilege: ") || lineLower.StartsWith("actionid: ") || lineLower.StartsWith("timestamp: ") || lineLower.StartsWith("server: ") ) { Helper.AddKeyValue(packet, line); } else { commandList.Add(line); } continue; } #endregion #region collect key: value and ProtocolIdentifier if (!string.IsNullOrEmpty(line)) { if (wait4identiier && line.StartsWith("Asterisk Call Manager")) { wait4identiier = false; var connectEvent = new ConnectEvent(mrConnector); connectEvent.ProtocolIdentifier = line; mrConnector.DispatchEvent(connectEvent); continue; } if (line.Trim().ToLower(Helper.CultureInfo) == "response: follows") { // Switch to wait "--END COMMAND--" mode processingCommandResult = true; packet.Clear(); commandList.Clear(); Helper.AddKeyValue(packet, line); continue; } Helper.AddKeyValue(packet, line); continue; } #endregion #region process events and responses if (packet.ContainsKey("event")) { mrConnector.DispatchEvent(packet); } else if (packet.ContainsKey("response")) { mrConnector.DispatchResponse(packet); } #endregion packet.Clear(); } if (mrSocket != null) { mrSocket.Close(); } break; } #if LOGGER catch (Exception ex) { logger.Info("Exception : {0}", ex.Message); #else catch { #endif } if (die) { break; } #if LOGGER logger.Info("No die, any error - send disconnect."); #endif mrConnector.DispatchEvent(new DisconnectEvent(mrConnector)); } }
public void Disconnect() { SocketConnection.Close(); }