Ejemplo n.º 1
0
        public NetworkConnection( Socket socket )
        {
            Contract.Requires( socket != null );
            Logger = new DefaultSessionLogger();
            Logger.Verbose( string.Format( "{0} NetworkConnection Constructor", socket.GetHashCode() ) );

            _socket = socket;

            _hasClosed = false;
            _hasShutdown = false;
        }
        public Client(Socket workerSocket)
        {
            Status = Client.ConnectionState.Waiting;
            socket = workerSocket;
            hash = socket.GetHashCode();

            FirstByte = new byte[1];
            LastByte = new byte[1];
            FirstByte[0] = 0x00;
            LastByte[0] = 0xFF;

            this.Established += HandleEstablished;
            this.Authenticated += HandleAuthenticated;
            waitForData();
        }
Ejemplo n.º 3
0
		public void GetHashCodeTest ()
		{
			Socket server = new Socket (AddressFamily.InterNetwork,
				SocketType.Stream, ProtocolType.Tcp);
			IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
							9010);
			server.Bind (ep);
			server.Listen (1);

			Socket client = new Socket (AddressFamily.InterNetwork, 
				SocketType.Stream, ProtocolType.Tcp);
			int hashcodeA = client.GetHashCode ();
			client.Connect (ep);
			int hashcodeB = client.GetHashCode ();
			Assert.AreEqual (hashcodeA, hashcodeB, "#1");
			client.Close ();
			int hashcodeC = client.GetHashCode ();
			Assert.AreEqual (hashcodeB, hashcodeC, "#2");
			server.Close ();
		}
Ejemplo n.º 4
0
        /// <summary>
        ///    <para>Set SocketOptionName.ReuseUnicastPort (SO_REUSE_UNICASTPORT) socket option on the outbound connection.</para>
        /// </summary>
        private void SetUnicastReusePortForSocket(Socket socket)
        {
            bool reusePort;
         
            if (ServicePointManager.ReusePortSupported.HasValue && !ServicePointManager.ReusePortSupported.Value) {
                // We tried to set the socket option before and it isn't supported on this system.  So, we'll save some
                // time by not trying again.
                reusePort = false;
            }
            else {
                reusePort = ServicePointManager.ReusePort;
            }

            if (reusePort) {
                // This socket option is defined in Windows 10.0 or later.  It is also
                // available if an LDR servicing patch has been installed on downlevel OS.
                try {
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 0x1);
                    if (Logging.On) { 
                        Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_set_socketoption_reuseport, 
                            "Socket", socket.GetHashCode()));
                    }
                    
                    ServicePointManager.ReusePortSupported = true;
                }
                catch (SocketException) {
                    // The socket option is not supported.  We will ignore this error and fail gracefully.
                    if (Logging.On) { 
                        Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_set_socketoption_reuseport_not_supported, 
                            "Socket", socket.GetHashCode()));
                    }                    
                    ServicePointManager.ReusePortSupported = false;
                }
                catch (Exception ex) {
                    // We want to preserve app compat and trap any other unusual exceptions.
                    if (Logging.On) { 
                        Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_unexpected_exception, ex.Message));
                    }
                }
            }            
        }
Ejemplo n.º 5
0
        public void ConnectAsync()
        {
            SocketAsyncEventArgs socketArgs;

            try
            {
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Logger.Network.Debug("Socket ID: " + _socket.GetHashCode().ToString() + "\r\nSocket created.");
            }
            catch (Exception e)
            {
                Logger.Network.Error("Socket ID: " + _socket.GetHashCode().ToString() + "\r\nAn exception occurred while instantiating the socket.", e);
                if (OnError != null)
                {
                    OnError(this, "Exception instantiating socket.", e);
                    return;
                }
                else throw;
            }

            try
            {
                _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, SendBufferSettings.Timeout);
                _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, ReceiveBufferSettings.Timeout);
                _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, SendBufferSettings.Size);
                _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, ReceiveBufferSettings.Size);
            }
            catch (Exception e)
            {
                Logger.Network.Error("Socket ID: " + _socket.GetHashCode().ToString() + "\r\nAn exception occurred while settings socket options.", e);
                if (OnError != null)
                {
                    OnError(this, "Exception settings socket options.", e);
                    return;
                }
                else throw;
            }

            lock (_socket)
            {
                socketArgs = new SocketAsyncEventArgs()
                {
                    RemoteEndPoint = EndPoint
                };
                socketArgs.Completed += new EventHandler<SocketAsyncEventArgs>(Connect_Completed);
                socketArgs.UserToken = new TcpConnectionAsyncEventArgs(new Timeout(SendBufferSettings.Timeout, Connect_Timeout));

                Logger.Network.Debug("Socket ID: " + _socket.GetHashCode().ToString() + "\r\nConnecting to " + EndPoint.Address.ToString() + " on " + EndPoint.Port.ToString() + "...");

                try
                {
                    if (!_socket.ConnectAsync(socketArgs))
                    {
                        Logger.Network.Debug("Socket ID: " + _socket.GetHashCode().ToString() + "\r\nConnectAsync completed synchronously.");
                        Connect_Completed(null, socketArgs);
                    }
                }
                catch (Exception e)
                {
                    Logger.Network.Error("Socket ID: " + _socket.GetHashCode().ToString() + "\r\nAn exception occurred while connecting the socket.", e);
                    if (OnError != null) OnError(this, "Exception connecting socket.", e);
                    else throw;
                }
            }
        }
Ejemplo n.º 6
0
		private void ProccessCommandCustom(BaseCommand command, Socket socket)
		{
			RenewSessionState(socket);
			if (OnCustomCommand != null)
			{
				OnCustomCommand(this, new CustomCommandEventArgs
				{
					Command = command,
					SessionId = socket.GetHashCode()
				});
			}
		}
Ejemplo n.º 7
0
		private void ProccessCommandRegist(CmdRegist cmdRegist, Socket socket)
		{
			RenewSessionState(socket);
			var sessionId = socket.GetHashCode();
			if (OnNewSession != null)
			{
				OnNewSession(this, new NewSessionEventArgs
				{
					PrevSessionId = cmdRegist.PrevSessionId,
					SessionId = sessionId
				});
			}
			Send(socket, new CmdRegistResp {
				 SessionId = sessionId
			});
		}
Ejemplo n.º 8
0
		private void RenewSessionState(Socket socket,bool registed= true) {
			int sessionId = socket.GetHashCode();
			rwlForSessionStateDict.AcquireReaderLock(int.MaxValue);
			try
			{
				if (sessionStateDict.ContainsKey(sessionId)) {
					var ss = sessionStateDict[sessionId];
					if (socket != ss.Socket)
						throw new Exception("socket not match");
					ss.LastRespondTime = DateTime.Now;
					ss.Registed = registed;
				}
			}
			catch (Exception)
			{

				throw;
			}
			finally
			{
				rwlForSessionStateDict.ReleaseReaderLock();
			}
		}
Ejemplo n.º 9
0
		private void ProcessNewConnection(Socket socket)
		{
			int sessionId = socket.GetHashCode();
			SessionState ss = new SessionState
			{
				Socket = socket,
				LastRespondTime = DateTime.Now,
				Registed = false,
				SessionId = sessionId
			};

			rwlForSessionStateDict.AcquireWriterLock(int.MaxValue);
			try
			{
				if (!sessionStateDict.ContainsKey(sessionId))
				{
					sessionStateDict.Add(sessionId, ss);
				}
				else {
					sessionStateDict[sessionId] = ss;
				}
			}
			catch (Exception)
			{
				throw;
			}
			finally
			{
				rwlForSessionStateDict.ReleaseWriterLock();
			}

		}