Esempio n. 1
0
        public static void CloseSock(ISocket socket, int timeout = 0)
        {
            if (socket.GetSocket().ProtocolType == ProtocolType.Tcp) socket.GetSocket().Shutdown(SocketShutdown.Both);

            if (timeout == 0) socket.Close();
            else socket.Close(timeout);
        }
Esempio n. 2
0
        public void FindDevices(TimeSpan timeout)
        {
            _socket = _socketFactory.CreateClientSocket();
            var request = _requestFactory.CreateMessage();
            var requestBytes = Encoding.ASCII.GetBytes(request);

            var responseThread = new Thread(GetSearchResponse);
            _socket.SendTo(requestBytes, new IPEndPoint(IPAddress.Parse(Constants.MulticastAddress), Constants.MulticastPort));
            responseThread.Start();
            Thread.Sleep(Convert.ToInt32(timeout.TotalMilliseconds));
            _socket.Close();
        }
Esempio n. 3
0
        public void Dispose()
        {
            CancelTokenSource.Cancel();

            ListenSocket?.Close();
            foreach (var client in ClientSockets.Keys)
            {
                client.Close();
            }

            if (ListenTasks.Count != 0)
            {
                Task.WaitAll(ListenTasks.ToArray());
            }
            ServerTask.Wait();
        }
Esempio n. 4
0
        public void Close()
        {
            if (!active)
            {
                if (logger.Enabled(LogType.Warning))
                {
                    logger.Log(LogType.Warning, "Peer is not active");
                }
                return;
            }
            active = false;
            Application.quitting -= Application_quitting;

            // send disconnect messages
            foreach (Connection conn in connections.Values)
            {
                conn.Disconnect(DisconnectReason.RequestedByLocalPeer);
            }
            RemoveConnections();

            // close socket
            socket.Close();
        }
Esempio n. 5
0
        public static void Shutdown(this ISocket socket)
        {
            var handle = (uint)socket.Handle;

            try
            {
                socket.Shutdown(SocketShutdown.Both);
            }
            catch
            {
            }

            try
            {
                socket.Close();
            }
            catch
            {
            }

            closesocket(handle);

            socket.Dispose();
        }
Esempio n. 6
0
        public bool Connect()
        {
            bool rt = false;

            try
            {
                //若Socket已经打开,则关闭
                if (ISocket != null && ISocket.Connected)
                {
                    ISocket.Shutdown(System.Net.Sockets.SocketShutdown.Both);
                    System.Threading.Thread.Sleep(100);
                    ISocket.Close();
                }

                //创建Socket对象(此处以TCP/IP协议创建对象,其他协议下创建对象的方法待完善)
                ISocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                                                        System.Net.Sockets.SocketType.Stream, SktProperty.ProtocolType);
                //定义服务器连接套接字
                System.Net.IPEndPoint iPEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(SktProperty.IP), SktProperty.Port);

                //非阻止模式连接到服务器端
                ISocket.Blocking = false;
                System.AsyncCallback OnConnected = new System.AsyncCallback(ConnectedCallBack);

                //异步请求连接到服务器端,当完成连接后回调:OnConnected委托
                ISocket.BeginConnect(iPEndPoint, OnConnected, ISocket);
                rt = true;
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
            return(rt);
        }
Esempio n. 7
0
 public void Reset()
 {
     ResetSections();
     if (Id < 255)
     {
         Main.player[Id] = new Player();
     }
     TimeOutTimer               = 0;
     StatusCount                = 0;
     StatusMax                  = 0;
     StatusText2                = "";
     StatusText                 = "";
     State                      = 0;
     _isReading                 = false;
     PendingTermination         = false;
     PendingTerminationApproved = false;
     SpamClear();
     IsActive = false;
     NetMessage.buffer[Id].Reset();
     if (Socket != null)
     {
         Socket.Close();
     }
 }
Esempio n. 8
0
        private void OnClientConnect(ISocket clientSocket)
        {
            if (clientSocket == null)
            {
                return;                       // socket closed
            }
            // experimental removed by wmp
            //FleckLog.Debug(String.Format("Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()));
            //Console.WriteLine(String.Format("Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()));

            string rep = string.Empty;

            bool failed = false;

            try {
                rep = clientSocket.RemoteIpAddress;
                Console.WriteLine("Connecting: " + rep);
            }
            catch {
                Console.WriteLine("Started but IP not available.");
                failed = true;
            }

            //ListenForClients();

            if (failed)
            {
                try{ clientSocket.Close(); }catch {}
                try{ clientSocket.Stream.Close(); }catch {}
                try{ clientSocket.Dispose(); }catch {}

                return;
            }


            WebSocketConnection connection = null;

            connection = new WebSocketConnection(
                clientSocket,
                _config,
                bytes => RequestParser.Parse(bytes, _scheme),
                r => HandlerFactory.BuildHandler(r,
                                                 s => connection.OnMessage(s),
                                                 connection.Close,
                                                 b => connection.OnBinary(b),
                                                 b => connection.OnPing(b),
                                                 b => connection.OnPong(b)),
                s => SubProtocolNegotiator.Negotiate(SupportedSubProtocols, s));

            if (IsSecure)
            {
                FleckLog.Debug("Authenticating Secure Connection");
                clientSocket
                .Authenticate(Certificate,
                              EnabledSslProtocols,
                              () =>
                {
                    Console.WriteLine("Authenticated {0}", rep);
                    Server.Firewall.Update(rep, Server.Firewall.UpdateEntry.AuthSuccess);
                    connection.StartReceiving();
                }
                              , e =>
                {
                    FleckLog.Warn("Failed to Authenticate " + rep, e);
                    // here we could add connection.Close() ! wmp
                    Server.Firewall.Update(rep, Server.Firewall.UpdateEntry.AuthFailure);
                    connection.Close();
                });
            }
            else
            {
                Server.Firewall.Update(rep, Server.Firewall.UpdateEntry.AuthSuccess);

                connection.StartReceiving();
            }
        }
Esempio n. 9
0
 public void Stop()
 {
     _listener?.Close();
 }
Esempio n. 10
0
 private static void OnDisconnect(ISocket obj)
 {
     obj.Close();
 }
Esempio n. 11
0
 public void Dispose()
 {
     _socket.Close();
 }
Esempio n. 12
0
 public override void Disconnect()
 {
     base.Disconnect();
     listenSocket.Close();
 }
Esempio n. 13
0
 public bool Close()
 {
     return(_socket.Close());
 }
Esempio n. 14
0
 private void Disconnect()
 {
     Socket?.Close();
     CancelTokenSource.Cancel();
     ListenTask?.Wait();
 }
Esempio n. 15
0
 private void ProxyThis(ISocket instream, ISocket outstream, AutoResetEvent readyToConnect)
 {
     Logger.Debug("Starting Proxy from " + instream + " to " + outstream);
     int read = 1;
     Closed = false;
     try
     {
         var inBuffer = new byte[_bufferSize];
         // listen for incoming connection
         if (!instream.Connected)
         {
             readyToConnect.Set();
             Logger.Debug("Listening for incoming connections");
             instream.ListenOnce();
             Logger.Debug("Connected incoming");
         }
         // connect to outgoing endpoint and start the reverse proxy
         if (!outstream.Connected)
         {
             outstream.Connect();
             Logger.Debug("Connected outgoing");
             _outRunner.Start();
             Logger.Debug("Started Reverse Proxy");
         }
         while (read > 0)
         {
             // Read from instream
             if (read > 0)
             {
                 try
                 {
                     read = instream.Read(inBuffer, _bufferSize);
     #if DEBUG
     //                            Logger.Debug("Read " + read + " bytes from " + instream);
     #endif
                 }
                 catch (Exception ex)
                 {
                     Logger.Error("Failed to read data from stream (" + instream + "), closing proxy : " + ex.Message);
                     break;
                 }
                 if (read > 0)
                 {
                     try
                     {
                         outstream.Send(inBuffer, read);
     #if DEBUG
                         //Logger.Debug("Wrote " + read + " bytes to " + outstream);
     #endif
                     }
                     catch (Exception ex)
                     {
                         Logger.Error("Failed to send data through stream (" + instream + ") , closing proxy : " + ex.Message);
                         break;
                     }
                 }
             }
             else
             {
                 Logger.Warn("Read no data from (" + instream + "), closing proxy");
             }
         }
     }
     catch (Exception ex)
     {
         Logger.Error("Thread caught exception while processing : " + ex.Message, ex);
     }
     finally
     {
         try
         {
             instream.Close();
         }
         catch (Exception ex)
         {
             Logger.Error("Caught Error closing stream (" + instream + ") : " + ex.Message, ex);
         }
         try
         {
             outstream.Close();
         }
         catch (Exception ex)
         {
             Logger.Error("Caught Error closing stream (" + outstream + ") : " + ex.Message, ex);
         }
     }
 }
Esempio n. 16
0
 private static void OnDisconnect(ISocket obj)
 {
     obj.Close();
 }
Esempio n. 17
0
 public void Disconnect()
 {
     clientSock_cliente.Close();
 }
Esempio n. 18
0
 public void Close()
 {
     sock.Close();
 }
Esempio n. 19
0
 public static void DisconnectSocket()
 {
     Socket.Close();
     Socket = null;
 }
Esempio n. 20
0
        private void ProxyThis(ISocket instream, ISocket outstream, AutoResetEvent readyToConnect)
        {
            Logger.Debug("Starting Proxy from " + instream + " to " + outstream);
            int read = 1;

            Closed = false;
            try
            {
                var inBuffer = new byte[_bufferSize];
                // listen for incoming connection
                if (!instream.Connected)
                {
                    readyToConnect.Set();
                    Logger.Debug("Listening for incoming connections");
                    instream.ListenOnce();
                    Logger.Debug("Connected incoming");
                }
                // connect to outgoing endpoint and start the reverse proxy
                if (!outstream.Connected)
                {
                    outstream.Connect();
                    Logger.Debug("Connected outgoing");
                    _outRunner.Start();
                    Logger.Debug("Started Reverse Proxy");
                }
                while (read > 0)
                {
                    // Read from instream
                    if (read > 0)
                    {
                        try
                        {
                            read = instream.Read(inBuffer, _bufferSize);
#if DEBUG
//                            Logger.Debug("Read " + read + " bytes from " + instream);
#endif
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("Failed to read data from stream (" + instream + "), closing proxy : " + ex.Message);
                            break;
                        }
                        if (read > 0)
                        {
                            try
                            {
                                outstream.Send(inBuffer, read);
#if DEBUG
                                //Logger.Debug("Wrote " + read + " bytes to " + outstream);
#endif
                            }
                            catch (Exception ex)
                            {
                                Logger.Error("Failed to send data through stream (" + instream + ") , closing proxy : " + ex.Message);
                                break;
                            }
                        }
                    }
                    else
                    {
                        Logger.Warn("Read no data from (" + instream + "), closing proxy");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Thread caught exception while processing : " + ex.Message, ex);
            }
            finally
            {
                try
                {
                    instream.Close();
                }
                catch (Exception ex)
                {
                    Logger.Error("Caught Error closing stream (" + instream + ") : " + ex.Message, ex);
                }
                try
                {
                    outstream.Close();
                }
                catch (Exception ex)
                {
                    Logger.Error("Caught Error closing stream (" + outstream + ") : " + ex.Message, ex);
                }
            }
        }
Esempio n. 21
0
        internal void Close(bool force_close)
        {
            if (sock != null)
            {
                if (!context.Request.IsWebSocketRequest || force_close)
                {
                    Stream st = GetResponseStream();
                    if (st != null)
                    {
                        st.Dispose();
                    }

                    o_stream = null;
                }
            }

            if (sock != null)
            {
                force_close |= !context.Request.KeepAlive;
                if (!force_close)
                {
                    force_close = (string.Equals(context.Response.Headers["connection"], "close", StringComparison.OrdinalIgnoreCase));
                }

                /*
                 *              if (!force_close) {
                 * //					bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
                 * //							status_code == 413 || status_code == 414 || status_code == 500 ||
                 * //							status_code == 503);
                 *                      force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
                 *              }
                 */

                if (!force_close && context.Request.FlushInput())
                {
                    reuses++;
                    Unbind();
                    Init();
                    BeginReadRequest();
                    return;
                }

                ISocket s = sock;
                sock = null;
                try
                {
                    if (s != null)
                    {
                        s.Shutdown(true);
                    }
                }
                catch
                {
                }
                finally
                {
                    if (s != null)
                    {
                        s.Close();
                    }
                }
                Unbind();
                RemoveConnection();
                return;
            }
        }
Esempio n. 22
0
        private static void OnConnectionAccepted(ISocket client)
        {
            int num = Netplay.FindNextOpenClientSlot();
            if (num != -1)
            {
                Netplay.Clients[num].Socket = client;
                Netplay.Clients[num].sendQueue.StartThread();

                Console.WriteLine(client.GetRemoteAddress() + " is connecting to slot {0}...", num);
            }
            else
            {
                using (var stream = new MemoryStream())
                {
                    using (var writer = new BinaryWriter(stream))
                    {
                        writer.Write((short)0);
                        writer.Write((byte)2);
                        writer.Write("Server is full.");
                        short position = (short)writer.BaseStream.Position;
                        writer.BaseStream.Position = 0L;
                        writer.Write((short)position);
                        byte[] data = stream.ToArray();
                        client.AsyncSend(data, 0, data.Length, delegate { });
                    }
                }
                client.Close();
            }
        }
Esempio n. 23
0
 public void Disconnect()
 {
     _socket?.Close();
 }
Esempio n. 24
0
 void IListenable.Close()
 {
     m_Socket.Close();
     m_Host.AcceptEvent -= Accept;
     m_Enable            = false;
 }
Esempio n. 25
0
 private void SocketClose()
 {
     _socket?.Close();
     _socket = null;
 }