コード例 #1
0
ファイル: NetServer.cs プロジェクト: orf53975/Ether.Network
        /// <inheritdoc />
        public void Start()
        {
            if (this.IsRunning)
            {
                throw new InvalidOperationException("Server is already running.");
            }

            this.CheckConfiguration();

            for (var i = 0; i < this.Configuration.MaximumNumberOfConnections; i++)
            {
                this._readPool.Push(NetUtils.CreateSocketAsync(null, this.IO_Completed, this.Configuration.BufferSize));
                this._writePool.Push(NetUtils.CreateSocketAsync(null, this.IO_Completed, this.Configuration.BufferSize));
            }

            this.Initialize();
            this.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            this.Socket.Bind(NetUtils.CreateIpEndPoint(this.Configuration.Host, this.Configuration.Port));
            this.Socket.Listen(this.Configuration.Backlog);
            this.IsRunning = true;
            this.StartAccept(NetUtils.CreateSocketAsync(null, this.IO_Completed));

            if (this.Configuration.Blocking)
            {
                this._manualResetEvent.WaitOne();
            }
        }
コード例 #2
0
        /// <summary>
        /// Connect to the remote host.
        /// </summary>
        public void Connect()
        {
            if (this.IsConnected)
            {
                throw new InvalidOperationException("Client is already connected to remote.");
            }

            var connectSocket = NetUtils.CreateSocketAsync(this.Socket, -1, this.IO_Completed);

            connectSocket.RemoteEndPoint = this._ipEndPoint;

            this.Socket.ConnectAsync(connectSocket);
            _autoConnectEvent.WaitOne();
            SocketError errorCode = connectSocket.SocketError;

            if (errorCode != SocketError.Success)
            {
                throw new SocketException((Int32)errorCode);
            }

            if (!this.Socket.ReceiveAsync(this._socketReceiveArgs))
            {
                this.ProcessReceive(this._socketReceiveArgs);
            }
        }
コード例 #3
0
 /// <summary>
 /// Creates a new <see cref="NetClient"/> instance.
 /// </summary>
 /// <param name="host">Remote host or ip</param>
 /// <param name="port">Remote port</param>
 /// <param name="bufferSize">Buffer size</param>
 public NetClient(string host, int port, int bufferSize)
 {
     this.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
     this._ipEndPoint        = NetUtils.CreateIpEndPoint(host, port);
     this._socketSendArgs    = NetUtils.CreateSocketAsync(this.Socket, -1, this.IO_Completed);
     this._socketReceiveArgs = NetUtils.CreateSocketAsync(this, bufferSize, this.IO_Completed);
     _autoConnectEvent       = new AutoResetEvent(false);
 }
コード例 #4
0
ファイル: NetClient.cs プロジェクト: orf53975/Ether.Network
        /// <inheritdoc />
        public void Connect()
        {
            if (this.IsRunning)
            {
                throw new InvalidOperationException("Client is already running");
            }

            if (this.IsConnected)
            {
                throw new InvalidOperationException("Client is already connected to remote.");
            }

            this.CheckConfiguration();

            this.Socket             = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this._socketSendArgs    = NetUtils.CreateSocketAsync(this.Socket, this.IO_Completed);
            this._socketReceiveArgs = NetUtils.CreateSocketAsync(this, this.IO_Completed, this.Configuration.BufferSize);

            SocketAsyncEventArgs connectSocket = NetUtils.CreateSocketAsync(this.Socket, this.IO_Completed);

            connectSocket.RemoteEndPoint = NetUtils.CreateIpEndPoint(this.Configuration.Host, this.Configuration.Port);

            if (this.Socket.ConnectAsync(connectSocket))
            {
                this._autoConnectEvent.WaitOne();
            }

            SocketError errorCode = connectSocket.SocketError;

            if (errorCode != SocketError.Success)
            {
                throw new SocketException((int)errorCode);
            }

            this._sendingQueueWorker.Start();
            this._receivingQueueWorker.Start();
            this.Token.Socket         = this.Socket;
            this.Token.MessageHandler = data => this._receivingQueue.Add(data, this._cancelToken);
            this.IsRunning            = true;

            if (!this.Socket.ReceiveAsync(this._socketReceiveArgs))
            {
                this.ProcessReceive(this._socketReceiveArgs);
            }
        }
コード例 #5
0
        /// <summary>
        /// Initialize and start the server.
        /// </summary>
        public void Start()
        {
            if (this.IsRunning)
                throw new InvalidOperationException("Server is already running.");

            if (this.Configuration.Port <= 0)
                throw new Exception($"{this.Configuration.Port} is not a valid port.");

            var address = this.Configuration.Host == AllInterfaces || Configuration.Host == null ? IPAddress.Any : this.Configuration.Address;
            if (address == null)
                throw new Exception($"Invalid host : {this.Configuration.Host}");
            myPoint = new IPEndPoint(address, this.Configuration.Port);
            this.Socket.Bind(myPoint);
            this.Socket.Listen(this.Configuration.Backlog);
            Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            this.StartAccept(NetUtils.CreateSocketAsync(null, -1, this.IO_Completed));
            this.IsRunning = true;
            Debug("服务器监听-->" + myPoint.ToString() + "<-----");
            IPPointByteList = myPoint.Address.GetAddressBytes();
        }
コード例 #6
0
        /// <summary>
        /// Process the accept connection async operation.
        /// </summary>
        /// <param name="e"></param>
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            try
            {
                if (e.SocketError == SocketError.Success)
                {
                    // SocketAsyncEventArgs readArgs = this._readPool.Pop();
                    //if(readArgs == null)

                    SocketAsyncEventArgs readArgs = NetUtils.CreateSocketAsync(null, this.Configuration.BufferSize, this.IO_Completed);

                    var client = new NetUser()
                    {
                        netServer = this,
                        Socket = e.AcceptSocket,
                        Id = e.AcceptSocket.RemoteEndPoint.GetHashCode(),
                    };
                    if (!this._clients.TryAdd(client.Id, client))
                        throw new Exception($"Client {client.Id} already exists in client list.");
                    Debug("上线-->" + e.AcceptSocket.RemoteEndPoint.ToString());
                    this.OnClientConnected(client);
                    readArgs.UserToken = client;
                    if (!e.AcceptSocket.ReceiveAsync(readArgs))
                        this.ProcessReceive(readArgs);

                }
            }
            catch (Exception exception)
            {
                Debug(exception.Message + "  " + exception.StackTrace);
                this.OnError(exception);
            }
            finally
            {
                this.StartAccept(e);
            }
        }
コード例 #7
0
        /// <inheritdoc />
        public void Connect()
        {
            if (this.IsRunning)
            {
                throw new InvalidOperationException("Client is already running");
            }

            if (this.IsConnected)
            {
                throw new InvalidOperationException("Client is already connected to remote.");
            }

            this.CheckConfiguration();

            this.Socket             = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this._socketSendArgs    = NetUtils.CreateSocketAsync(this.Socket, this.IO_Completed);
            this._socketReceiveArgs = NetUtils.CreateSocketAsync(this, this.IO_Completed, this.Configuration.BufferSize);

            SocketAsyncEventArgs connectSocket = NetUtils.CreateSocketAsync(this.Socket, this.IO_Completed);

            connectSocket.RemoteEndPoint = NetUtils.CreateIpEndPoint(this.Configuration.Host, this.Configuration.Port);

            SocketError errorCode = ConnectSocketToServer(connectSocket);

            if (!IsConnected)
            {
                if (this.Configuration.RetryMode == NetClientRetryOptions.Limited)
                {
                    int count = 0;

                    while (!IsConnected && count < this.Configuration.MaxRetryAttempts)
                    {
                        errorCode = ConnectSocketToServer(connectSocket);
                        count++;
                    }
                }
                else if (this.Configuration.RetryMode == NetClientRetryOptions.Infinite)
                {
                    while (!IsConnected)
                    {
                        errorCode = ConnectSocketToServer(connectSocket);
                    }
                }

                if (!IsConnected)
                {
                    this.OnSocketError(errorCode);
                    return;
                }
            }

            this._sendingQueueWorker.Start();
            this._receivingQueueWorker.Start();
            this.Token.Socket         = this.Socket;
            this.Token.MessageHandler = data => this._receivingQueue.Add(data, this._cancelToken);
            this.IsRunning            = true;

            if (!this.Socket.ReceiveAsync(this._socketReceiveArgs))
            {
                this.ProcessReceive(this._socketReceiveArgs);
            }
        }