Exemple #1
0
        /// <summary>
        /// 启动服务
        /// </summary>
        /// 时间:2016/6/7 22:54
        /// 备注:
        /// <exception cref="System.InvalidOperationException">未能成功创建Socket服务类型。</exception>
        public void Start()
        {
            listener = GetCorrectSocket();
            #region 解决UDP错误10054:远程主机强迫关闭了一个现有的连接
            if (Protocol == SocketProtocol.UDP)
            {
                uint IOC_IN            = 0x80000000;
                uint IOC_VENDOR        = 0x18000000;
                uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
                listener.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
                listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            #endregion
            if (listener != null)
            {
                listener.Bind(this.Endpoint);

                if (this.Protocol == SocketProtocol.TCP)
                {
                    listener.Listen(this.MaxQueuedConnections);
                    listener.BeginAccept(new AsyncCallback(ClientConnected), listener);
                }
                else if (Protocol == SocketProtocol.UDP)
                {
                    SocketConnectionInfo _connection = new SocketConnectionInfo();
                    _connection.Buffer = new byte[SocketConnectionInfo.BufferSize];
                    _connection.Socket = listener;
                    ipeSender          = new IPEndPoint(IPAddress.Any, this.Port);
                    listener.BeginReceiveFrom(_connection.Buffer, 0, _connection.Buffer.Length, SocketFlags.None, ref ipeSender, new AsyncCallback(DataReceived), _connection);
                }

                SocketServerStartedEventArgs _arg = new SocketServerStartedEventArgs
                {
                    Protocol     = this.Protocol,
                    SocketServer = this.Endpoint,
                    StartedTime  = DateTime.Now
                };
                OnServerStarted.RaiseEvent(this, _arg);
            }
            else
            {
                throw new InvalidOperationException("未能成功创建Socket服务类型。");
            }
        }
Exemple #2
0
 private static void _server_OnServerStart(object sender, SocketServerStartedEventArgs e)
 {
     Console.WriteLine(e.SocketServer + " " + "启动成功。");
 }