コード例 #1
0
 /// <summary>
 /// 断开与服务端连接
 /// </summary>
 public void Close()
 {
     // 关闭客户端心跳
     isHeartBeat = false;
     // 关闭客户端连接
     clientSocket.Close();
 }
コード例 #2
0
        private void OnMessageReceived(IAsyncResult asyncResult)
        {
            try
            {
                int numberOfBytesRead = ClientSocket.EndReceive(asyncResult);
                if (numberOfBytesRead > 0)
                {
                    string message = Encoding.UTF8.GetString(ReceivedBuffer, 0, numberOfBytesRead);

                    Console.WriteLine("[Client] Received: {0}",
                                      message);

                    ClientSocket.BeginReceive(ReceivedBuffer, 0,
                                              ReceivedBuffer.Length, SocketFlags.None,
                                              OnMessageReceived,
                                              null);
                }
                else
                {
                    ClientSocket.Shutdown(SocketShutdown.Both);
                    ClientSocket.Close();
                }
            }
            catch (Exception exception)
            {
            }
        }
コード例 #3
0
ファイル: PopClient.cs プロジェクト: WolfeReiter/PopFree
        public void Dispose()
        {
            if (!Disposing)
            {
                Disposing = true;

                if (TryGetConnected())
                {
                    try
                    {
                        ClientSocket.ReceiveTimeout = 500;
                        ClientSocket.SendTimeout    = 500;
                        try
                        {
                            SendQuit();
                        }
                        catch (IOException) { }
                        catch (PopServerResponseErrException) { }
                        ClientSocket.Close();
                        StreamReader.Close();
                        StreamWriter.Close();
                    }
                    catch (ObjectDisposedException) { }
                    finally
                    {
                        StreamReader = null;
                        StreamWriter = null;
                        ClientSocket = null;
                    }
                }
            }
        }
コード例 #4
0
ファイル: TcpClient.cs プロジェクト: gkurbesov/C4C.Socket
 /// <summary>
 /// Отключение сокета от сервера
 /// </summary>
 public void Disconnect()
 {
     lock (locker)
     {
         if (ClientSocket != null)
         {
             try
             {
                 LingerOption lingerOption = new LingerOption(true, 1);
                 ClientSocket.LingerState = lingerOption;
                 ClientSocket.Shutdown(SocketShutdown.Both);
             }
             catch (Exception ex)
             {
                 CallErrorClient(ClientErrorType.CloseConnection, "Error in Shutdown - " + ex.Message);
             }
             try
             {
                 ClientSocket.Close();
                 ClientSocket.Dispose();
             }
             finally
             {
                 ClientSocket = null;
             }
         }
         if (ConnectedStatus)
         {
             ConnectedStatus = false;
             CallDisconnected();
         }
     }
 }
コード例 #5
0
 public void Close(Action callback = null)
 {
     if (ClientSocket == null)
     {
         return;
     }
     try
     {
         if (IsConnected)
         {
             ClientSocket.Shutdown(SocketShutdown.Both);
         }
         if (ClientSocket != null)
         {
             ClientSocket.Close();
             if (ClientSocket != null)
             {
                 ClientSocket.Dispose();
             }
             ClientSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源
         }
         sendQueue.Clear();
         isSending = false;
         callback?.Invoke();
     }
     catch (Exception E)
     {
         Console.WriteLine(E.Message);
     }
 }
コード例 #6
0
ファイル: Client.cs プロジェクト: ramss22/Seringa
 ///<summary>Disposes of the resources (other than memory) used by the Client.</summary>
 ///<remarks>Closes the connections with the local client and the remote host. Once <c>Dispose</c> has been called, this object should not be used anymore.</remarks>
 ///<seealso cref ="System.IDisposable"/>
 public void Dispose()
 {
     try {
         ClientSocket.Shutdown(SocketShutdown.Both);
     } catch {}
     try {
         DestinationSocket.Shutdown(SocketShutdown.Both);
     } catch {}
     //Close the sockets
     if (ClientSocket != null)
     {
         ClientSocket.Close();
     }
     if (DestinationSocket != null)
     {
         DestinationSocket.Close();
     }
     //Clean up
     ClientSocket      = null;
     DestinationSocket = null;
     if (Destroyer != null)
     {
         Destroyer(this);
     }
 }
コード例 #7
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }
            if (disposing)
            {
                if (session != null)
                {
                    try
                    {
                        Server.GlobalInstance.ClientSockets.Remove(session);
                        session.Close();
                        session = null;
                    }
                    catch { }
                }

                if (ClientSocket != null)
                {
                    try
                    {
                        ClientSocket.Close();
                        ClientSocket.Dispose();
                        ClientSocket = null;
                    }
                    catch { }
                }
            }
            disposed = true;
        }
コード例 #8
0
 private void GetMessage()
 {
     try
     {
         while (true)
         {
             Stream = ClientSocket.GetStream();
             int    bufferSize = ClientSocket.ReceiveBufferSize;
             byte[] buffer     = new byte[bufferSize];
             int    bytes      = Stream.Read(buffer, 0, buffer.Length);
             string message    = Encoding.Unicode.GetString(buffer, 0, bytes);
             if (!IsReceivedInfo)
             {
                 ClientIP       = message.Split(':')[0];
                 ClientPort     = message.Split(':')[1].Split('/')[0];
                 IsReceivedInfo = !IsReceivedInfo;
             }
             if (message == "")
             {
                 ClientSocket.Close();
             }
             DisplayText(message);
         }
     }
     catch (Exception ex)
     {
         try
         {
             this.Invoke(new DelegateDisconnect(DisconnectSocket));
             this.Invoke(new DelegateButtonChange(ButtonStatusChange));
         }
         catch { }
         IsReceivedInfo = false;
     }
 }
コード例 #9
0
        public void CloseConnection()
        {
            lock (clientLocker)
            {
                if (ClientConnected)
                {
                    try
                    {
                        ClientWriter.WriteLine("-- " + Properties.strings.cya);
                        ClientWriter.Flush();
                    }
                    catch (IOException) { }
                    ConnectedServer.WriteToAllClients("-- " + string.Format(Properties.strings.disconnectedClient,
                                                                            Name + "@" + ClientIep.Address, ClientIep.Port));

                    ClientWriter.Close();
                    ClientReader.Close();
                    ClientStream.Close();
                    ClientSocket.Close();
                    ClientConnected = false;
                    ConnectedServer.connectedClients.Remove(this);
                }
            }
            ConnectedServer.RefreshInfo();
        }
コード例 #10
0
ファイル: UdpClient.cs プロジェクト: gkurbesov/C4C.Socket
 /// <summary>
 /// Отключение сокета от сервера
 /// </summary>
 public void Disconnect()
 {
     if (ClientSocket != null)
     {
         lock (ClientSocket)
         {
             try
             {
                 ClientSocket.Shutdown(SocketShutdown.Both);
             }
             catch (Exception ex)
             {
                 CallErrorClient(ClientErrorType.CloseConnection, "Error in Shutdown - " + ex.Message);
             }
         }
         if (ClientSocket != null)
         {
             ClientSocket.Close();
             ClientSocket.Dispose();
         }
         ClientSocket = null;
     }
     if (ConnectedStatus)
     {
         CallDisconnected();
     }
     ConnectedStatus = false;
 }
コード例 #11
0
 ///<summary>Disposes of the resources (other than memory) used by the Client.</summary>
 ///<remarks>Closes the connections with the local client and the remote host. Once <c>Dispose</c> has been called, this object should not be used anymore.</remarks>
 ///<seealso cref ="System.IDisposable"/>
 public void Dispose()
 {
     try
     {
         ClientSocket.Shutdown(SocketShutdown.Both);
     }
     catch { }
     try
     {
         DestinationSocket.Shutdown(SocketShutdown.Both);
     }
     catch { }
     //Close the sockets
     if (ClientSocket != null)
     {
         ClientSocket.Close();
     }
     if (DestinationSocket != null)
     {
         DestinationSocket.Close();
     }
     //Clean up
     CompleteSendBuffer = string.Empty;
     CompleteReadBuffer = string.Empty;
     ClientSocket       = null;
     DestinationSocket  = null;
     if (Destroyer != null)
     {
         Destroyer(this);
     }
 }
コード例 #12
0
 public void Disconnect()
 {
     _server.AddLogMsg($"Disconnecting client{Id}");
     ClientSocket.Shutdown(SocketShutdown.Both);
     ClientSocket.Close();
     _server.AddLogMsg($"Client{Id} disconnected");
 }
コード例 #13
0
 public void Close()
 {
     //schließen
     Send(endMessage);
     ClientSocket.Close(1);
     clientReceiveThread.Abort();
 }
コード例 #14
0
ファイル: Clients.cs プロジェクト: gleborgs/AsyncRAT-C-Sharp
        public void Disconnected()
        {
            try
            {
                if (LV != null)
                {
                    if (Program.form1.listView1.InvokeRequired)
                    {
                        Program.form1.listView1.BeginInvoke((MethodInvoker)(() =>
                        {
                            LV.Remove();
                        }));
                    }
                    lock (Settings.Online)
                        Settings.Online.Remove(this);
                }
            }
            catch { }

            try
            {
                ClientSslStream?.Close();
                ClientSocket?.Close();
                ClientSslStream?.Dispose();
                ClientSocket?.Dispose();
                ClientMS?.Dispose();
            }
            catch { }
        }
コード例 #15
0
 public void Dispose()
 {
     try
     {
         if (ClientSocket != null)
         {
             ClientSocket.Shutdown(SocketShutdown.Both);
         }
     }
     catch
     {
     }
     try
     {
         if (DestinationSocket != null)
         {
             DestinationSocket.Shutdown(SocketShutdown.Both);
         }
     }
     catch
     {
     }
     ClientSocket?.Close();
     DestinationSocket?.Close();
     ClientSocket      = null;
     DestinationSocket = null;
     _destroyer?.Invoke(this);
 }
コード例 #16
0
 private void _Close()
 {
     ClientSocket.Close();
     ClientSocket = null;
     Disconnected?.Invoke(this, EventArgs.Empty);
     Logger.Debug("ソケットを閉じました。");
 }
コード例 #17
0
        public virtual void ShutdownConnection()
        {
            Running = false;

            ClientSocket.Shutdown(SocketShutdown.Both);
            ClientSocket.Close();
        }
コード例 #18
0
 private void RX()
 {
     try
     {
         while (true)
         {
             try
             {
                 if (!ClientSocket.Connected)
                 {
                     Logger.NetworkChatLog($"User with IP: {ClientIP}:{ClientPort}, Disconnected from the Network chat. Connection time: {(DateTime.Now - this.ConnectedAt)}. ChatClientID: {this.ClientID}");
                     MainManager.onMessage              -= msgdelegate;
                     NetworkEvents.onPlayerConnected    -= onPlayerConnectedDelegate;
                     NetworkEvents.onPlayerDisconnected -= onPlayerDisconnectedDelegate;
                     MainManager.ChatClients.Remove(this);
                     return;
                 }
                 byte[] buffer = new byte[ClientSocket.ReceiveBufferSize];
                 ClientSocket.Receive(buffer);
                 if (String.IsNullOrEmpty(Encoding.UTF8.GetString(buffer)))
                 {
                     continue;
                 }
                 if (lastMessageTime != null)
                 {
                     if (!this.IsAdmin)
                     {
                         if ((DateTime.Now - lastMessageTime).TotalSeconds < MainManager.ChatCooldown) //too Fast
                         {
                             InfoSender($"You chatting too fast, send message every {MainManager.ChatCooldown} second/s");
                             continue;
                         }
                     }
                 }
                 string[] serial         = Encoding.UTF8.GetString(buffer).Split('|');
                 string   sender_name    = serial[1];
                 string   sender_message = serial[2];
                 MainManager.SendMessagetoChatLocal(sender_name, sender_message);
                 Logger.NetworkChatLog($"(networkuser) {sender_name}: {sender_message} . ChatClientID: {this.ClientID}");
                 lastMessageTime = DateTime.Now;
             }
             catch { lastMessageTime = DateTime.Now; Thread.Sleep(1000); continue; }
         }
     }
     catch
     {
         try
         {
             ClientSocket.Close();
             Logger.NetworkChatLog($"User with IP: {ClientIP}:{ClientPort}, Disconnected from the Network chat. Connection time: {(DateTime.Now - this.ConnectedAt)} . ChatClientID: {this.ClientID} ");
         }
         catch { MainManager.ChatClients.Remove(this); Logger.NetworkChatLog($"User with IP: {ClientIP}:{ClientPort}, Disconnected from the Network chat. Connection time: {(DateTime.Now - this.ConnectedAt)} . ChatClientID: {this.ClientID}"); return; }
         MainManager.onMessage              -= msgdelegate;
         NetworkEvents.onPlayerConnected    -= onPlayerConnectedDelegate;
         NetworkEvents.onPlayerDisconnected -= onPlayerDisconnectedDelegate;
         MainManager.ChatClients.Remove(this);
         return;
     }
 }
コード例 #19
0
 private void StopConnect()
 {
     if (ClientSocket.Connected)
     {
         ClientSocket.Shutdown(SocketShutdown.Both);
         ClientSocket.Close(100);
     }
 }
コード例 #20
0
ファイル: Form1.cs プロジェクト: ainochi-kor/HowToCSharp
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     try
     {
         ClientSocket.Close();
     }
     catch { }
 }
コード例 #21
0
 // Callback, called when the ping method times out
 private void OnTimeOut(object state)
 {
     HasTimeOut = true;
     if (ClientSocket != null)
     {
         ClientSocket.Close();                 // This will result in a throw of a SocketException in Ping() method
     }
 }
コード例 #22
0
 /// <summary>
 /// 断开连接
 /// </summary>
 public void Disconnect()
 {
     cache.Clear();                              // 清空缓冲区
     isProcessingReceive = false;
     ClientSocket.Shutdown(SocketShutdown.Both); // 禁用发送和接收
     ClientSocket.Close();
     ClientSocket = null;
 }
コード例 #23
0
 /// <summary>
 /// Закрытие все покдлючений к серверу
 /// </summary>
 public void CloseAllSockets()
 {
     foreach (Socket ClientSocket in _ClientSockets)
     {
         ClientSocket.Send(_Encoder.GetBytes("Сервер выключен. Соединение разорванно!"));
         ClientSocket.Shutdown(SocketShutdown.Both);
         ClientSocket.Close();
     }
 }
コード例 #24
0
    public void Close()
    {
        if (clientSocket != null)
        {
            clientSocket.Close();

            clientSocket = null;
        }
    }
コード例 #25
0
 public void Close()
 {
     if (null != socket)
     {
         socket.Close();
     }
     socket = null;
     m_parseBufferOffset = 0;
 }
コード例 #26
0
 /// <summary>
 /// 断开服务器
 /// </summary>
 public void stopClient()
 {
     byte[] type     = new byte[2];
     byte[] mainData = new byte[8];
     byte[] md5pwd   = TCPClient.Md5pwd;
     mainData = Encoding.UTF8.GetBytes("已人为退出");
     SendData(md5pwd, mainData);
     ClientSocket.Close();
 }
コード例 #27
0
ファイル: SocketClient.cs プロジェクト: thoemmi/haacked.com
 // Disposes managed resources
 void DisposeManagedResources()
 {
     Log.Info(_id + ": Closing down SocketClient.");
     if (ClientSocket.Connected)
     {
         ClientSocket.Shutdown(SocketShutdown.Both);
     }
     ClientSocket.Close();
 }
コード例 #28
0
 /// <summary>
 /// Called when the ping method times out.
 /// </summary>
 /// <param name="state">The source of the event. This is an object containing application-specific information relevant to the methods invoked by this delegate, or a null reference (Nothing in Visual Basic).</param>
 protected void PingTimedOut(object state)
 {
     HasTimedOut = true;
     // Close the socket (this will result in a throw of a SocketException in the Ping method)
     if (ClientSocket != null)
     {
         ClientSocket.Close();
     }
 }
コード例 #29
0
 private void DisconnectSocket()
 {
     try
     {
         ClientSocket.Close();
     }
     catch (Exception ex)
     { }
 }
コード例 #30
0
ファイル: IBClient.cs プロジェクト: svengl/IBNet
 /// <summary>
 /// The bulk of the clean-up code is implemented in Dispose(bool)
 /// </summary>
 /// <param name="disposing">Allows the ondispose method to override the dispose action.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         GeneralTracer.WriteLineIf(ibTrace.TraceInfo, "IBClient Dispose");
         ClientSocket.eDisconnect();
         ClientSocket.Close();
     }
 }
コード例 #31
0
ファイル: ConsoleClient.cs プロジェクト: byteshadow/bolt
        private static void BoltClientSocket()
        {
            _clientSocket = new ClientSocket();
            _clientSocket.Connect("tcp://127.0.0.1:9900");
            _clientSocket.MessageProcessor.MessageBroker.Subscribe<RequestMessage>(MessageHandler);
            _cancellationToken = new CancellationTokenSource();

            Task.Factory.StartNew(SendMessages, _cancellationToken.Token);

            Console.ReadLine();
            _clientSocket.Close();
        }
コード例 #32
0
ファイル: BoltSocketTests.cs プロジェクト: byteshadow/bolt
        public void AyncTcpServer()
        {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.Bind(9900);

            serverSocket.AddMessageHandler<SampleMessage>(SampleMessageHandler);

            // Get host related information.
            IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;

            // Get endpoint for the listener.
            IPEndPoint localEndPoint = new IPEndPoint(addressList[addressList.Length - 1], 9900);

            long totalTime = 0;
            const int msgs = (int)1e5;
            int msgLength = 0;
            Action action = () =>
                {
                    ClientSocket clientSocket = new ClientSocket();
                    clientSocket.Connect(localEndPoint);

                    Assert.IsTrue(clientSocket.Connected);

                    Stopwatch sw = Stopwatch.StartNew();
                    Serializer serializer = new Serializer();

                    var sample = new SampleMessage { X = 38 };
                    var msg = serializer.Serialize(sample);
                    msgLength = msg.Length;

                    for (int i = 0; i < msgs; i++)
                    {
                        clientSocket.Send(sample);
                    }

                    sw.Stop();

                    Interlocked.Add(ref totalTime, sw.ElapsedMilliseconds);

                    SpinWait.SpinUntil(() => counter == msgs, 2000);

                    //networkStream.Close();
                    clientSocket.Close();
                };

            List<Action> actions = new List<Action>();
            int numOfClients = 1;

            for (int i = 0; i < numOfClients; i++)
            {
                actions.Add(action);
            }

            Stopwatch sw2 = Stopwatch.StartNew();
            Parallel.Invoke(actions.ToArray());

            if (!Debugger.IsAttached)
                SpinWait.SpinUntil(() => counter == msgs * numOfClients, 2000);
            else
            {
                SpinWait.SpinUntil(() => counter == msgs * numOfClients, 60000);
            }

            sw2.Stop();

            Console.WriteLine("Num Of Msgs: {0:###,###}", counter);
            Console.WriteLine("Average for each client {0}ms", totalTime / actions.Count);
            Console.WriteLine("Average Speed for each client: {0:###,###}msgs/s", (msgs / (totalTime / actions.Count)) * 1000);
            Console.WriteLine("Total time: {0}ms", sw2.ElapsedMilliseconds);
            Console.WriteLine("Msgs/s {0:###,###}", (counter / sw2.ElapsedMilliseconds) * 1000);
            Console.WriteLine("Msg length {0}bytes", msgLength);
            Assert.AreEqual(msgs * numOfClients, counter, "Not all msgs received");
        }