BeginAccept() public method

public BeginAccept ( AsyncCallback callback, object state ) : IAsyncResult
callback AsyncCallback
state object
return IAsyncResult
コード例 #1
1
ファイル: Listener.cs プロジェクト: Crome696/ServUO
		public Listener(IPEndPoint ipep)
		{
			m_Accepted = new Queue<Socket>();
			m_AcceptedSyncRoot = ((ICollection)m_Accepted).SyncRoot;

			m_Listener = Bind(ipep);

			if (m_Listener == null)
			{
				return;
			}

			DisplayListener();

#if NewAsyncSockets
			m_EventArgs = new SocketAsyncEventArgs();
			m_EventArgs.Completed += new EventHandler<SocketAsyncEventArgs>( Accept_Completion );
			Accept_Start();
            #else
			m_OnAccept = OnAccept;
			try
			{
				IAsyncResult res = m_Listener.BeginAccept(m_OnAccept, m_Listener);
			}
			catch (SocketException ex)
			{
				NetState.TraceException(ex);
			}
			catch (ObjectDisposedException)
			{ }
#endif
		}
コード例 #2
0
ファイル: SocketServer.cs プロジェクト: difros/REPO-ts-day
 private void SetUpServer(int countReintentos = 0)
 {
     try
     {
         if (ListenerSocker == null)
         {
             return;
         }
         ListenerSocker.Bind(new IPEndPoint(IPAddress.Any, port));
         ListenerSocker.Listen(0x7FFFFFFF);
         ListenerSocker.BeginAccept(new AsyncCallback(AcceptCallback), null);
     }
     catch (Exception e)
     {
         Log.Log.GetLog().Error(this, "SetUpServer", e);
         Thread.Sleep(5000);
         if (countReintentos > 10)
         {
             Log.Log.GetLog().Info(this, "Fin Reintentos - SetUpServer - " + countReintentos);
             return;
         }
         Log.Log.GetLog().Info(this, "Reintentando - SetUpServer - " + countReintentos);
         SetUpServer(countReintentos + 1);
     }
 }
コード例 #3
0
ファイル: Program.cs プロジェクト: Zeroeh/PrivateServerOld
        //Main
        static void Main(string[] args)
        {
            ILog log = LogManager.GetLogger(typeof(Program)); //Added
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            svrSkt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            svrSkt.Bind(new IPEndPoint(IPAddress.Any, 2050));
            svrSkt.Listen(0xff);
            svrSkt.BeginAccept(Listen, null);
            Console.CancelKeyPress += (sender, e) =>
            {
                Console.WriteLine("Saving Please Wait...");
                svrSkt.Close();
                foreach (var i in RealmManager.Clients.Values.ToArray())
                {
                    i.Save();
                    i.Disconnect();
                }
                Console.WriteLine("\nClosing...");
                Thread.Sleep(100);
                Environment.Exit(0);
            };

            Console.ForegroundColor = ConsoleColor.Green;
            Console.Title = "Server Engine";
            Console.WriteLine("Accepting connections at port " + port + ".");
            HostPolicyServer();
            RealmManager.CoreTickLoop();
        }
コード例 #4
0
ファイル: MusSocket.cs プロジェクト: BjkGkh/Jamal2.5
        internal MusSocket(String _musIp, int _musPort, String[] _allowedIps, int backlog)
        {
            musIp = _musIp;
            musPort = _musPort;

            allowedIps = new HashSet<String>();

            foreach (String ip in _allowedIps)
            {
                allowedIps.Add(ip);
            }

            try
            {
                msSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                msSocket.Bind(new IPEndPoint(IPAddress.Any, musPort));
                msSocket.Listen(backlog);

                msSocket.BeginAccept(OnEvent_NewConnection, msSocket);

                Logging.WriteLine("MUS socket -> READY!", ConsoleColor.Green);
            }

            catch (Exception e)
            {
                throw new ArgumentException("Could not set up MUS socket:\n" + e.ToString());
            }
        }
コード例 #5
0
        // (1) Establish The Server
        public string Start_A_Server_On(int Port)
        {
            try
            {
                IPAddress[] AddressAr = null;
                String ServerHostName = "";

                try
                {
                    ServerHostName = Dns.GetHostName();
                    IPHostEntry ipEntry = Dns.GetHostByName(ServerHostName);
                    AddressAr = ipEntry.AddressList;
                }
                catch (Exception) { }

                if (AddressAr == null || AddressAr.Length < 1)
                {
                    return "Unable to get local address ... Error";
                }

                Listener_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                Listener_Socket.Bind(new IPEndPoint(AddressAr[0], Port));
                Listener_Socket.Listen(-1);

                Listener_Socket.BeginAccept(new AsyncCallback(EndAccept), Listener_Socket);

                return ("Listening On " + AddressAr[0].ToString() + ":" + Port + "... OK");

            }
            catch (Exception ex) { return ex.Message; }
        }
コード例 #6
0
        public void ConnectMaster()
        {
            if (c_Connected && c_Server)
                return;

            try
            {
                c_Server = true;
                //Console.WriteLine("CM Close Slave");
                CloseSlave();

                c_Master = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                c_Master.Bind(new IPEndPoint(IPAddress.Any, Data.MultiPort));
                c_Master.Listen(4);
                c_Master.BeginAccept(new AsyncCallback(OnClientConnect), null);
                //Console.WriteLine("Started");

                c_Connecting = false;
                c_Connected = true;
            }
            catch (Exception /*e*/)// I HID e to stop warning message.
            {
                c_Server = false;
                //Console.WriteLine(e.Message);
                //Console.WriteLine(e.StackTrace);
            }
        }
コード例 #7
0
ファイル: SGSserverForm.cs プロジェクト: iukash/TcpServerChat
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //We are using TCP sockets
                serverSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);

                //Assign the any IP of the machine and listen on port number 1000
                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 1000);

                //Bind and listen on the given address
                serverSocket.Bind(ipEndPoint);
                serverSocket.Listen(4);

                //Accept the incoming clients
                serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSserverTCP",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #8
0
ファイル: Listener.cs プロジェクト: acid1789/DECO
        private void OnClientConnect(IAsyncResult AcceptAsync)
        {
            try
            {
                Socket Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Sock = ListenerSock.EndAccept(AcceptAsync);
                Server ServerSock = new Server(Sock);
                //RaiseEvent if event is linked
                if (Connected != null)
                {
                    Connected(ServerSock);
                }
            }
            catch
            {

            }
            finally
            {
                ListenerSock.Dispose();
                ListenerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress hostIP = (Dns.Resolve(IPAddress.Any.ToString())).AddressList[0];
                ListenerSock.Bind(new IPEndPoint(hostIP, m_Port));
                ListenerSock.Listen(0);
                ListenerSock.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
        }
コード例 #9
0
ファイル: SocketServer.cs プロジェクト: anthrax3/ide-1
        public static void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                System.Net.Sockets.Socket workerSocket = m_mainSocket.EndAccept(asyn);
                Interlocked.Increment(ref m_clientCount);
                m_workerSocketList.Add(workerSocket);

                WaitForData(workerSocket, m_clientCount);
                string msg = "Client " + m_clientCount + " Connected" + "\n";
                if (OutputClientChanged != null)
                {
                    OutputClientChanged(null, msg);
                }
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
            }
        }
コード例 #10
0
 public void StartServer()
 {
     try
     {
         //creez un soclu
         listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         //se creeza un endpoint pentru server
         IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse(IP), 8888);
         //setez endpoint-ul creat
         listener.Bind(ipLocal);
         //soclul trece in starea de ascultare;coada de asteptare este de 4 clienti
         listener.Listen(4);
         list = new ArrayList(4);
         //incep ascultarea neblocanta a conexiunilor
         //orice incercare de conectare va fi tratata de metoda OnClientConnect
         listener.BeginAccept(new AsyncCallback(OnClientConnect), null);
         //creez delegatul pentru afisarea mesajelor
         DelegateShowText = new Action<string, Socket>(ShowText);
         //atashez un handler pt schimbarea textului
         rt.TextChanged += new System.EventHandler(textChanged);
         DelegateSendText = new Action<Socket>(SendText);
     }
     catch (SocketException se)
     {
         MessageBox.Show(se.Message);
     }
 }
コード例 #11
0
ファイル: Program.cs プロジェクト: artemsv/HttpServer
        static void Main(string[] args)
        {
            Console.WriteLine("Hello from Console C# Classic HTTP Server");

            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

            Socket listener = new Socket(SocketType.Stream, ProtocolType.Tcp);

            listener.Bind(localEndPoint);
            listener.Listen(100);

            Console.ReadLine();

            while (true)
            {
                // Set the event to nonsignaled state.
                //allDone.Reset();

                // Start an asynchronous socket to listen for connections and receive data from the client.
                Console.WriteLine("Waiting for a connection...");

                // Accept the connection and receive the first 10 bytes of data.
                int receivedDataSize = 10;
                listener.BeginAccept(receivedDataSize, new AsyncCallback(AcceptReceiveCallback), listener);

                // Wait until a connection is made and processed before continuing.
                //allDone.WaitOne();
            }
        }
コード例 #12
0
ファイル: KSocket.cs プロジェクト: tmbx/etkwm
        /// <summary>
        /// Create 2 sockets connected to each other, for communication between threads.
        /// </summary>
        public static Socket[] SocketPair()
        {
            Socket Listener;
            Socket[] Pair = new Socket[2];

            // Start the listener side.
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 0);
            Listener = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            Listener.Bind(endPoint);
            Listener.Listen(1);
            IAsyncResult ServerResult = Listener.BeginAccept(null, null);

            // Connect the client to the server.
            endPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)Listener.LocalEndPoint).Port);
            Pair[0] = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            IAsyncResult ClientResult = Pair[0].BeginConnect(endPoint, null, null);

            // Get the server side socket.
            Pair[1] = Listener.EndAccept(ServerResult);
            Pair[0].EndConnect(ClientResult);

            Listener.Close();

            Pair[0].Blocking = false;
            Pair[1].Blocking = false;

            return Pair;
        }
コード例 #13
0
ファイル: ServerTerminal.cs プロジェクト: liuwei0925/myPrj
        public void StartListen(int port)
        {
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);

            m_socket = new Socket(AddressFamily.InterNetwork, 
                SocketType.Stream, ProtocolType.Tcp);
            
            //bind to local IP Address...
            //if ip address is allready being used write to log
            try
            {
                m_socket.Bind(ipLocal);
            }
            catch(Exception ex)
            {
                Debug.Fail(ex.ToString(),
                    string.Format("Can't connect to port {0}!", port));
                
                return;
            }
            //start listening...
            m_socket.Listen(4);
            // create the call back for any client connections...
            m_socket.BeginAccept(new AsyncCallback(OnClientConnection), null);
            
        }
コード例 #14
0
ファイル: Server.cs プロジェクト: evelinad/Talk2Me
        public static void Main(string[] args)
        {
            Console.Out.WriteLine("This is the server");

            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, listenPort);
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                while (true)
                {
                    acceptDone.Reset();

                    Console.Out.WriteLine("Listening on port {0}", listenPort);
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

                    acceptDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #15
0
ファイル: Server.cs プロジェクト: BRampersad/SimChat
        /// <summary>
        /// Listens this instance.
        /// </summary>
        public void Listen()
        {
            Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                Listener.Bind(EndPoint);
                Listener.Listen(100);

                while (true)
                {
                    // Make the work signal nonsignaled
                    Done.Reset();

                    Listener.BeginAccept(AcceptCallback, Listener);

                    // Wait until we get a connection
                    Done.WaitOne();
                }
            }
            catch (Exception e)
            {

                Console.WriteLine(e.ToString());
            }
        }
コード例 #16
0
ファイル: Server.cs プロジェクト: mfussenegger/papercut
        public void Bind()
        {
            try
            {
                // Load IP/Port settings
                if (Settings.Default.IP == "Any")
                    _address = IPAddress.Any;
                else
                    _address = IPAddress.Parse(Settings.Default.IP);
                _port = Settings.Default.Port;

                // If the listener isn't null, close before rebinding
                if (_listener != null)
                    _listener.Close();

                // Bind to the listening port
                _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _listener.Bind(new IPEndPoint(_address, _port));
                _listener.Listen(10);
                _listener.BeginAccept(new AsyncCallback(OnClientAccept), null);
                Logger.Write("Server Ready - Listening for new connections " + _address + ":" + _port + "...");
            }
            catch (Exception ex)
            {
                Logger.WriteError("Exception thrown in Server.Start()", ex);
                throw;
            }
        }
コード例 #17
0
 private void StartListening()
 {
     _ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     _ListenSocket.Bind(new IPEndPoint(IPAddress.Any, _ListenPort));
     _ListenSocket.Listen(10);
     _ListenSocket.BeginAccept(AcceptCallback, null);
 }
コード例 #18
0
ファイル: SocketServer.cs プロジェクト: anthrax3/ide-1
        public static string StartListen(string IPadress, string portStr)
        {
            try
            {
                IPAddress ipAddress = IPAddress.Parse(IPadress);

                int port = System.Convert.ToInt32(portStr);

                m_mainSocket = new  System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream,
                                                              ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(ipAddress, port);                //(IPAddress.Any, port);

                m_mainSocket.Bind(ipLocal);

                m_mainSocket.Listen(4);

                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
                isRunning = true;
                return(ipLocal.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
                return(null);
            }
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: Team694/kinect-CAD
 public static void beginListening()
 {
     listenS = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     listenS.Bind(new IPEndPoint(IPAddress.Any, PORT));
     listenS.Listen(4);
     listenS.BeginAccept(new AsyncCallback(OnCallAccept), null);
 }
コード例 #20
0
ファイル: Gateway.cs プロジェクト: KaskidFoundations/ucs
        public bool Host(int port)
        {
            //Dev View
            //Console.WriteLine("Hosting on port " + port);

            m_vServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                m_vServerSocket.Bind(new IPEndPoint(IPAddress.Any, port));
                m_vServerSocket.Listen(kHostConnectionBacklog);
                m_vServerSocket.BeginAccept(new System.AsyncCallback(OnClientConnect), m_vServerSocket);
            }
            catch (System.Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Exception when attempting to host (" + port + "): " + e);
                Console.ResetColor();
                m_vServerSocket = null;

                return false;
            }

            return true;
        }
コード例 #21
0
ファイル: ServiceHost.cs プロジェクト: zlphoenix/LearnCSharp
        /// <summary>
        /// 启动服务,打开TCP监听端口
        /// </summary>
        public void Start()
        {
            tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                // Create a TCP/IP socket.
                tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                IPEndPoint localEndPoint = null;
                //Listen Connection from All IP 
                localEndPoint = new IPEndPoint(IPAddress.Any, config.LocalPort);


                // Bind the socket to the local endpoint and listen for incoming connections.
                tcpSocket.Bind(localEndPoint);
                tcpSocket.Listen(1024);
                // Upload an asynchronous socket to listen for connections.
                Logging.Info("ServiceHost started");
                tcpSocket.BeginAccept(AcceptCallback, tcpSocket);
            }
            catch (SocketException ex)
            {
                Logging.LogUsefulException(ex);
                tcpSocket.Close();
                throw;
            }
        }
コード例 #22
0
ファイル: SocketServer.cs プロジェクト: Zane0816/Mail-.Net
        public static void StartServer()
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址:端口  
                serverSocket.Listen(10);    //设定最多10个排队连接请求   

                Console.WriteLine("启动监听{0}成功\n", serverSocket.LocalEndPoint.ToString());
                while (true)
                {
                    allDone.Reset();
                    serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket);
                    allDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            //通过Clientsoket发送数据  
            //Thread myThread = new Thread(ListenClientConnect);
            //myThread.Start();
            Console.ReadLine();

        }
コード例 #23
0
ファイル: Server.cs プロジェクト: aiex/AsyncSockets
 private void _acceptConnection()
 {
     Core.EventLoop.Instance.Push(() =>
     {
         nativeSocket.BeginAccept(_static_endAccept, this);
     });
 }
コード例 #24
0
ファイル: Program.cs プロジェクト: lcnvdl/rotmg-server
        static void Main(string[] args)
        {
            try
            {
                svrSkt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                svrSkt.Bind(new IPEndPoint(IPAddress.Any, 2050));
                svrSkt.Listen(0xff);
                svrSkt.BeginAccept(Listen, null);
                Console.CancelKeyPress += (sender, e) =>
                {
                    Console.WriteLine("Terminating...");
                    svrSkt.Close();
                    foreach (var i in RealmManager.Clients.Values.ToArray())
                        i.Disconnect();
                    Environment.Exit(0);
                };
                Console.WriteLine("Listening at port 2050...");

                HostPolicyServer();

                RealmManager.CoreTickLoop();    //Never returns
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
                Console.ReadLine();
            }
        }
コード例 #25
0
ファイル: Server.cs プロジェクト: tuita520/Regulus
        private void Accept(IAsyncResult Ar)
        {
            try
            {
                var socket = m_Socket.EndAccept(Ar);
                lock (Acctpe)
                {
                    Acctpe(new Peer(socket));
                }

                m_Socket.BeginAccept(Accept, state: null);
            }


            catch (SocketException se)
            {
                Singleton <Log> .Instance.WriteInfo(se.ToString());
            }
            catch (ObjectDisposedException ode)
            {
                Singleton <Log> .Instance.WriteInfo(ode.ToString());
            }
            catch (InvalidOperationException ioe)
            {
                Singleton <Log> .Instance.WriteInfo(ioe.ToString());
            }
            catch (Exception e)
            {
                Singleton <Log> .Instance.WriteInfo(e.ToString());
            }
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: cvanherk/3d-engine
        private static void Main(string[] args)
        {
            //init
            IsRunning = false;
            LastTime = 0;
            CurrentTime = 0;
            Connections = new List<Connection>(Config.MaxPlayers);
            DisconnectedConnections = new List<Connection>(Config.MaxPlayers);
            
            try
            {
                //maakt ipendpoint voor server listening
                //luistert naar 
                var ip = IPAddress.Parse("0.0.0.0");
                var iPEndPoint = new IPEndPoint(ip, Config.ServerPort);
                _serverListenerSocket = new Socket(iPEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                _serverListenerSocket.Bind(iPEndPoint);
                _serverListenerSocket.Listen(25);
                _serverListenerSocket.BeginAccept(new AsyncCallback(acceptCallback), _serverListenerSocket);

                IsRunning = true;
                Debugging.WriteLine($"--[{Config.ServerName} started on port {Config.ServerPort}]--", ConsoleColor.Red);
                //start de game update thread.
                new Thread(new ThreadStart(GameThread)).Start();
            }
            catch (SocketException ioe)
            {
                Debugging.WriteLine($"Error: {ioe.Message}", ConsoleColor.Red);

                IsRunning = false;
            }
        }
コード例 #27
0
ファイル: MicroHttpServer.cs プロジェクト: rameshr/NLog
 public void Start()
 {
     socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     socket.Bind(new IPEndPoint(IPAddress.Loopback, this.ListenPort));
     socket.Listen(10);
     socket.BeginAccept(OnAccept, null);
 }
コード例 #28
0
ファイル: SocketServer.cs プロジェクト: arissetyawan/rhodes
        private void start_listening()
        {
            try
            {

                if (m_logPath != null)
                    File.Delete(m_logPath);
                // Create the listening socket...
                m_mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, PORT);
                // Bind to local IP Address...
                m_mainSocket.Bind(ipLocal);
                // Start listening...
                m_mainSocket.Listen(1000);
                // Create the call back for any client connections...
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
                // m_mainSocket.BeginAccept(new AsyncCallback(AcceptCallback), m_mainSocket);

            }
            catch (Exception se)
            {
                Environment.Exit(0);
            }

        }
コード例 #29
0
ファイル: Tracker.cs プロジェクト: edwardsamuel/Gunbond
        public Tracker(string configfile)
        {
            Configuration = new TrackerConfig(configfile);
            Logger.Active = Configuration.Log;

            peers = new Dictionary<int, Peer>();
            rooms = new Dictionary<string, Room>();

            // Listening on socket
            IPAddress ipAddr = IPAddress.Parse(Configuration.IPAddress);
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, Configuration.Port);
            SocketPermission permission = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", Configuration.Port);
            permission.Demand();

            try
            {
                listener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                listener.Bind(ipEndPoint);

                Console.WriteLine("Listening at IP " + ipEndPoint.Address + " and port " + ipEndPoint.Port + ".");

                listener.Listen(Configuration.Backlog);

                AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
                listener.BeginAccept(aCallback, listener);
            }
            catch (SocketException exc)
            {
                Logger.WriteLine(exc);
            }
        }
コード例 #30
0
        /// <summary> 
        /// Initializes the socket listener for MUS connections and starts listening. 
        /// </summary> 
        /// <param name="bindPort">The port where the socket listener should be bound to.</param> 
        /// <remarks></remarks> 
        internal static bool Init(int bindPort, string musHost)
        {
            _Port = bindPort;
            _musHost = musHost;
            socketHandler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            Out.WriteLine("Starting up asynchronous socket server for MUS connections for port " + bindPort + "...");
            try
            {
                socketHandler.Bind(new IPEndPoint(IPAddress.Any, bindPort));
                socketHandler.Listen(25);
                socketHandler.BeginAccept(new AsyncCallback(connectionRequest), socketHandler);

                Out.WriteLine("Asynchronous socket server for MUS connections running on port " + bindPort);
                Out.WriteLine("Listening for MUS connections from " + musHost);
                return true;
            }

            catch
            {
                Out.WriteError("Error while setting up asynchronous socket server for MUS connections on port " + bindPort);
                Out.WriteError("Port " + bindPort + " could be invalid or in use already.");
                return false;
            }
        }
コード例 #31
0
        public void Start(IPAddress address, int?port)
        {
            var localEndPoint = new IPEndPoint(address, port.HasValue ? port.Value : DEFAULT_PORT);

            _socket = new System.Net.Sockets.Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                _socket.Bind(localEndPoint);
                _socket.Listen(BACKLOG);

                Console.WriteLine("Server started. Listening to TCP clients at {0}:{1}", address.ToString(), localEndPoint.Port);

                while (true)
                {
                    _event.Reset();
                    _socket.BeginAccept(new AsyncCallback(AcceptCallback), this);
                    Console.WriteLine("Waiting for a connection...");
                    _event.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #32
0
ファイル: MusSocket.cs プロジェクト: sgf/Yupi
        internal MusSocket(string musIp, int musPort, IEnumerable<string> allowedIps, int backlog)
        {
            MusIp = musIp;
            MusPort = musPort;
            AllowedIps = new HashSet<string>();
            foreach (var item in allowedIps) AllowedIps.Add(item);
            try
            {
                Out.WriteLine(
                    "Starting up asynchronous sockets server for MUS connections for port " +
                    musPort, "Server.AsyncSocketMusListener");

                MsSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                MsSocket.Bind(new IPEndPoint(IPAddress.Any, MusPort));
                MsSocket.Listen(backlog);
                MsSocket.BeginAccept(OnEvent_NewConnection, MsSocket);

                Out.WriteLine(
                    "Asynchronous sockets server for MUS connections running on port " +
                    musPort + Environment.NewLine,
                    "Server.AsyncSocketMusListener");
            }
            catch (Exception ex)
            {
                throw new ArgumentException($"No se pudo iniciar el Socket MUS:\n{ex}");
            }
        }
コード例 #33
0
        /// <summary> 
        /// Initializes the socket listener for game connections and starts listening. 
        /// </summary> 
        /// <param name="bindPort">The port where the socket listener should be bound to.</param> 
        /// <param name="maxConnections">The maximum amount of simultaneous connections.</param> 
        /// <remarks></remarks> 
        internal static bool Init(int bindPort, int maxConnections)
        {
            _Port = bindPort;
            _maxConnections = maxConnections;
            _activeConnections = new HashSet<int>();
            socketHandler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            Out.WriteLine("Starting up asynchronous socket server for game connections for port " + bindPort + "...");
            try
            {
                socketHandler.Bind(new IPEndPoint(IPAddress.Any, bindPort));
                socketHandler.Listen(25);
                socketHandler.BeginAccept(new AsyncCallback(connectionRequest), socketHandler);

                Out.WriteLine("Asynchronous socket server for game connections running on port " + bindPort);
                Out.WriteLine("Max simultaneous connections is " + maxConnections);
                return true;
            }

            catch
            {
                Out.WriteError("Error while setting up asynchronous socket server for game connections on port " + bindPort);
                Out.WriteError("Port " + bindPort + " could be invalid or in use already.");
                return false;
            }
        }
コード例 #34
0
ファイル: GameGuardServer.cs プロジェクト: stephenZh/l2net
        private void button_gg_listen_Click(object sender, EventArgs e)
        {
            Globals.gamedata.GG_IP = textBox_gg_local_ip.Text;
            Globals.gamedata.GG_Port = Util.GetInt32(textBox_gg_local_port.Text);
            System.Net.IPAddress ipAd = System.Net.IPAddress.Parse(Globals.gamedata.GG_IP);

            Globals.GG_Servermode = true;
            try
            {
                // Create the listening socket...
                m_mainSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(ipAd, Globals.gamedata.GG_Port);
                // Bind to local IP Address...
                m_mainSocket.Bind(ipLocal);
                // Start listening...
                m_mainSocket.Listen(4);
                // Create the call back for any client connections...
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

            button_gg_listen.Enabled = false;
            Globals.l2net_home.Add_Text(String.Format("Gameguard server started on: {0}:{1}", Globals.gamedata.GG_IP, Globals.gamedata.GG_Port), Globals.Yellow, TextType.BOT);
            this.Close();
        }
コード例 #35
0
ファイル: GameGuardServer.cs プロジェクト: stephenZh/l2net
        public static void pre_listen()
        {
            System.Net.IPAddress ipAd = System.Net.IPAddress.Parse(Globals.gamedata.GG_IP);

            Globals.GG_Servermode = true;
            try
            {
                // Create the listening socket...
                m_mainSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(ipAd, Globals.gamedata.GG_Port);
                // Bind to local IP Address...
                m_mainSocket.Bind(ipLocal);
                // Start listening...
                m_mainSocket.Listen(4);
                // Create the call back for any client connections...
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

            Globals.l2net_home.Add_Text(String.Format("Gameguard server started on: {0}:{1}", Globals.gamedata.GG_IP, Globals.gamedata.GG_Port), Globals.Yellow, TextType.BOT);
        }
コード例 #36
0
        void OnNewClient(IAsyncResult _asyncResult)
        {
            System.Net.Sockets.Socket ClientSocket = ListenSocket.EndAccept(_asyncResult);
            ListenSocket.BeginAccept(OnNewClient, null);

            SetKeepAlive(ClientSocket, 1000 * 60, 1000);

            var NewClient = new TelnetClient {
                Socket = ClientSocket
            };

            if (Clients.ClientConnected(NewClient) == ClientAcceptanceStatus.Rejected)
            {
                NewClient.WasRejected = true;
                ClientSocket.Close();
            }
            else
            {
                // We will handle all the echoing echoing echoing
                //var echoCommand = new byte[]
                //{
                //    (byte)TelnetControlCodes.IAC,
                //    (byte)TelnetControlCodes.Will, // TODO: Handle client response denying this request
                //    (byte)TelnetControlCodes.Echo,
                //    (byte)TelnetControlCodes.IAC,
                //    (byte)TelnetControlCodes.Dont,
                //    (byte)TelnetControlCodes.Echo,
                //};
                //ClientSocket.Send(echoCommand);

                ClientSocket.BeginReceive(NewClient.Storage, 0, 1024, System.Net.Sockets.SocketFlags.Partial, OnData, NewClient);
                Console.WriteLine("New telnet client: " + ClientSocket.RemoteEndPoint.ToString());
            }
        }
コード例 #37
0
        public static void StartListening(int port = 11001)
        {
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = IPAddress.Parse(LocalSettings.ServerIP);
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
            _allDone = new ManualResetEvent(false);
            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);
                while (true)
                {
                    // Set the event to nonsignaled state.
                    _allDone.Reset();
                    // Start an asynchronous socket to listen for connections.
                    listener.BeginAccept(
                        AcceptCallback,
                        listener);
                    // Wait until a connection is made before continuing.
                    _allDone.WaitOne();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }
コード例 #38
0
 private void OnConnectRequest(IAsyncResult ar)
 {
     try
     {
         System.Net.Sockets.Socket listener = (System.Net.Sockets.Socket)ar.AsyncState;
         NewConnection(listener.EndAccept(ar));
         listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
     }
     catch { }
 }
コード例 #39
0
 void StartListeningSocket(IPAddress addr, int port)
 {
     socket = new System.Net.Sockets.Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try {
         socket.Bind(new IPEndPoint(addr, port));
         socket.Listen(128);
         socket.BeginAccept(AcceptCallback, null);
     } catch {
     }
 }
コード例 #40
0
ファイル: SocketServer.cs プロジェクト: Cliveburr/BlueDB
        public void Start(IPAddress address, int port)
        {
            Listener = new System.Net.Sockets.Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint = new IPEndPoint(address, port);
            Listener.Bind(IPEndPoint);
            Listener.Listen(100);

            Listener.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }
コード例 #41
0
ファイル: Server.cs プロジェクト: tuita520/Regulus
        void IListenable.Bind(int Port)
        {
            m_Socket         = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_Socket.NoDelay = true;


            m_Socket.Bind(new IPEndPoint(IPAddress.Any, Port));
            m_Socket.Listen(backlog: 5);
            m_Socket.BeginAccept(Accept, state: null);
        }
コード例 #42
0
        /// <summary>
        /// Puts the socket in a listen state.
        /// Waiting for connections
        /// </summary>
        /// <exception cref="Exception">Socket already bound or connected</exception>
        public void Listen()
        {
            if (_socket.IsBound || _socket.Connected)
            {
                throw new Exception("Unable to listen. Socket already bound or connected.");
            }

            try
            {
                CreateEndPoint();
                _socket.Bind(IpEndPoint);
                _socket.Listen(40);
                _socket.BeginAccept(OnAcceptCallback, _socket);
            }
            catch (Exception e)
            {
                throw new Exception("Couldn't start the socket (port: " + _port + ") in listening mode.\n" + e.Message);
            }
        }
コード例 #43
0
 //クライアントの接続待ちスタート
 private static void StartAccept(System.Net.Sockets.Socket server)
 {
     while (true)
     {
         //接続要求待機を開始する
         allDone.Reset();
         server.BeginAccept(new System.AsyncCallback(AcceptCallback), server);
         Console.WriteLine("Waiting for a connection...");
         allDone.WaitOne();
     }
 }
コード例 #44
0
        private void OnClientConnect(IAsyncResult result)
        {
            xConnection conn = new xConnection();

            try
            {
                //Finish accepting the connection
                Socket s = (Socket)result.AsyncState;
                conn        = new xConnection();
                conn.socket = s.EndAccept(result);
                conn.buffer = new byte[_bufferSize];
                lock (_sockets)
                {
                    _sockets.Add(conn);
                }


                // if (ClientConnected != null)
                //   ClientConnected();

                Console.WriteLine("[SRV] client connected");

                //Queue recieving of data from the connection
                conn.socket.BeginReceive(conn.buffer, 0, conn.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveData), conn);
                //Queue the accept of the next incomming connection
                _serverSocket.BeginAccept(new AsyncCallback(OnClientConnect), _serverSocket);
            }
            catch (Exception e)
            {
                if (conn.socket != null)
                {
                    conn.socket.Close();
                    lock (_sockets)
                    {
                        _sockets.Remove(conn);
                    }
                }
                //Queue the next accept, think this should be here, stop attacks based on killing the waiting listeners
                _serverSocket.BeginAccept(new AsyncCallback(OnClientConnect), _serverSocket);
            }
        }
コード例 #45
0
        void AcceptCallback(IAsyncResult ar)
        {
            try {
                var sock = socket.EndAccept(ar);

                loop.NonBlockInvoke(delegate {
                    acceptedCallback(new Socket(loop, sock));
                });
                socket.BeginAccept(AcceptCallback, null);
            } catch {
            }
        }
コード例 #46
0
        void AcceptCallback(IAsyncResult ar)
        {
            try {
                var sock = socket.EndAccept(ar);

                Enqueue(delegate {
                    acceptedCallback(new Socket(Context, sock));
                });
            } catch {
            }
            socket.BeginAccept(AcceptCallback, null);
        }
コード例 #47
0
        private void acceptCallback(IAsyncResult result)
        {
            xConnection conn = null;             // new xConnection();

            try {
                //Finish accepting the connection
                System.Net.Sockets.Socket s = (System.Net.Sockets.Socket)result.AsyncState;
                conn        = new xConnection();
                conn.socket = s.EndAccept(result);
                conn.buffer = new byte[_bufferSize];
                conn.server = this;
                lock (_sockets) {
                    _sockets.Add(conn);
                }
                //Queue recieving of data from the connection
                conn.socket.BeginReceive(conn.buffer, 0, conn.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), conn);
                //Queue the accept of the next incomming connection
                _serverSocket.BeginAccept(new AsyncCallback(acceptCallback), _serverSocket);
            } catch (SocketException) {
                if (conn.socket != null)
                {
                    conn.socket.Close();
                    lock (_sockets) {
                        _sockets.Remove(conn);
                    }
                }
                //Queue the next accept, think this should be here, stop attacks based on killing the waiting listeners
                _serverSocket.BeginAccept(new AsyncCallback(acceptCallback), _serverSocket);
            } catch (Exception) {
                if (conn.socket != null)
                {
                    conn.socket.Close();
                    lock (_sockets) {
                        _sockets.Remove(conn);
                    }
                }
                //Queue the next accept, think this should be here, stop attacks based on killing the waiting listeners
                _serverSocket.BeginAccept(new AsyncCallback(acceptCallback), _serverSocket);
            }
        }
コード例 #48
0
        private void ListenCallback(IAsyncResult ar)
        {
            try {
                System.Net.Sockets.Socket listener = ar.AsyncState as System.Net.Sockets.Socket;
                if (listener == null)
                {
                    //throw (new Exception("Listener Socket no longer exists"));
                    Exceptions.ErrorLogger.WriteToErrorLog(new Exception("Listener socket no longer exists"), "Listener socket no longer exists");
                }

                //CErrorLogger.WriteToErrorLog(new Exception("Listen callback hit"), "Listen callback hit");

                System.Net.Sockets.Socket client = listener.EndAccept(ar);

                if (listening != true)
                {
                    listener.Close();
                    return;
                }

                int index = FindOpenIndex();
                if (index == -1)
                {
                    Exceptions.ErrorLogger.WriteToErrorLog(new Exception("Server Full"), "Server Full");
                    client.Close();
                }
                else
                {
                    clients[index] = client;
                    connectionCallback(this, new ConnectionRecievedEventArgs(client.RemoteEndPoint, client, index));

                    DataAsyncState state = new DataAsyncState(bufferSize, client, index);
                    if (client.Connected)
                    {
                        client.BeginReceive(state.Data, 0, bufferSize, SocketFlags.None,
                                            new AsyncCallback(RecieveCallback), state);
                    }
                }
                listener.BeginAccept(new AsyncCallback(ListenCallback), listener);
            } catch (ObjectDisposedException ex) {
                Exceptions.ErrorLogger.WriteToErrorLog(ex, "Disposed exception, server listener.");
                serverSocket.BeginAccept(new AsyncCallback(ListenCallback), serverSocket);
                return;
            } catch (SocketException socketex) {
                Exceptions.ErrorLogger.WriteToErrorLog(socketex, "Socket exception, server listener.");
                RaiseError(socketex.Message, "", (SocketError)socketex.ErrorCode);
                serverSocket.BeginAccept(new AsyncCallback(ListenCallback), serverSocket);
            } catch (Exception ex) {
                Exceptions.ErrorLogger.WriteToErrorLog(ex, "Normal exception, server listener.");
                serverSocket.BeginAccept(new AsyncCallback(ListenCallback), serverSocket);
            }
        }
コード例 #49
0
        public void Listen()
        {
            ListenSocket = new System.Net.Sockets.Socket(
                System.Net.Sockets.AddressFamily.InterNetwork,
                System.Net.Sockets.SocketType.Stream,
                System.Net.Sockets.ProtocolType.IP);

            ListenSocket.Bind(new System.Net.IPEndPoint(0, Port));
            ListenSocket.Listen(16);
            ListenSocket.BeginAccept(OnNewClient, null);

            Console.WriteLine("Listening on port " + Port);
        }
コード例 #50
0
        internal void OnAcceptReceived(IAsyncResult ar)
        {
            System.Net.Sockets.Socket sman = (System.Net.Sockets.Socket)ar.AsyncState;

            if (sman != null)
            {
                System.Net.Sockets.Socket newsocket = null;
                try
                {
                    newsocket = sman.EndAccept(ar);
                }
                catch (System.ObjectDisposedException e)
                {
                    System.Diagnostics.Debug.WriteLine("Exception calling EndAccept {0}", e);
                    return;
                }
                catch (System.Exception eall)
                {
                    System.Diagnostics.Debug.WriteLine("Exception calling EndAccept - continueing {0}", eall);
                }

                /// Start a new accept
                try
                {
                    sman.BeginAccept(AcceptCallback, sman);
                }
                catch (SocketException e3) /// winso
                {
                    System.Diagnostics.Debug.WriteLine("Exception calling BeginAccept2 {0}", e3);
                }
                catch (ObjectDisposedException e4) // socket was closed
                {
                    System.Diagnostics.Debug.WriteLine("Exception calling BeginAccept2 {0}", e4);
                }
                catch (System.Exception eall)
                {
                    System.Diagnostics.Debug.WriteLine("Exception calling BeginAccept2 {0}", eall);
                }

                if (newsocket == null)
                {
                    return;
                }

                System.Diagnostics.Debug.WriteLine("Accepted new socket {0}", newsocket.Handle);
                if (OnNewConnection != null)
                {
                    OnNewConnection(newsocket);
                }
            }
        }
コード例 #51
0
ファイル: SocketServer.cs プロジェクト: Tamerz/MBBSEmu
        public void Start(EnumSessionType sessionType, int port, string moduleIdentifier = null)
        {
            _sessionType      = sessionType;
            _moduleIdentifier = moduleIdentifier;

            //Setup Listener
            var ipEndPoint = new IPEndPoint(IPAddress.Any, port);

            _listenerSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _listenerSocket.Bind(ipEndPoint);
            _listenerSocket.Listen(10);
            _listenerSocket.BeginAccept(OnNewConnection, this);
        }
コード例 #52
0
        public void StartServer()
        {
            //  IPHostEntry localhost = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            IPEndPoint serverEndPoint;

            serverEndPoint = new IPEndPoint(IPAddress.Any, PORT);
            _serverSocket  = new Socket(serverEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            _serverSocket.Bind(serverEndPoint);
            _serverSocket.Listen(10);
            _serverSocket.BeginAccept(new AsyncCallback(OnClientConnect), _serverSocket);

            _authorizedClients = ClientUtil.GetClients();
            Console.WriteLine("[SRV] server started");
        }
コード例 #53
0
        /// <summary>
        /// 启动监听的端口
        /// </summary>
        /// <param name="port">要监听的端口号</param>
        /// <param name="localaddr">要绑定的ip地址</param>
        /// <param name="reuseAddress">是否运行端口复用</param>
        public virtual void Start(int port, IPAddress localaddr = null, bool reuseAddress = true)
        {
            var serverSocketEP = new IPEndPoint(localaddr ?? IPAddress.Any, port);

            serverSocket = new Socket(serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            if (reuseAddress)
            {
                //serverSocket.ExclusiveAddressUse = true;
                serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            serverSocket.Bind(serverSocketEP);
            serverSocket.Listen(int.MaxValue);
            serverSocket.BeginAccept(AcceptSocketCallback, serverSocket);
            IsStart = true;
            WriteLog($"服务启动,监听IP:{serverSocketEP.Address},端口:{port}");
        }
コード例 #54
0
        private void OnNewConnection(IAsyncResult asyncResult)
        {
            System.Net.Sockets.Socket client;
            try
            {
                client = _listenerSocket.EndAccept(asyncResult);
            } catch (ObjectDisposedException) {
                // ignore, happens during shutdown
                return;
            }

            client.NoDelay = true;

            _listenerSocket.BeginAccept(OnNewConnection, this);

            switch (_sessionType)
            {
            case EnumSessionType.Telnet:
            {
                _logger.Info($"Accepting incoming Telnet connection from {client.RemoteEndPoint}...");
                var session = new TelnetSession(_host, _logger, client, _configuration, _textVariableService);
                _host.AddSession(session);
                session.Start();
                break;
            }

            case EnumSessionType.Rlogin:
            {
                if (((IPEndPoint)client.RemoteEndPoint).Address.ToString() != _configuration.RloginRemoteIP)
                {
                    _logger.Info(
                        $"Rejecting incoming Rlogin connection from unauthorized Remote Host: {client.RemoteEndPoint}");
                    client.Close();
                    return;
                }

                _logger.Info($"Accepting incoming Rlogin connection from {client.RemoteEndPoint}...");
                var session = new RloginSession(_host, _logger, client, _channelDictionary, _configuration, _textVariableService, _moduleIdentifier);
                _host.AddSession(session);
                session.Start();
                break;
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
コード例 #55
0
        private void AcceptCallback(IAsyncResult ar)
        {
            System.Net.Sockets.Socket socket;

            try
            {
                socket = _serverSocket.EndAccept(ar);
                _clientSockets.Add(socket);
                socket.BeginReceive(_buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket);
                Console.WriteLine("Client connected: " + socket.RemoteEndPoint);
                _serverSocket.BeginAccept(AcceptCallback, null);
            }
            catch (Exception e)
            {
                // Log.Error
            }
        }
コード例 #56
0
 /// <summary>
 /// Setup the server
 /// </summary>
 public void SetupServer()
 {
     try
     {
         Console.WriteLine("Setting up server...");
         _serverSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         _serverSocket.Bind(new IPEndPoint(IPAddress.Any, _port));
         _serverSocket.Listen(5);
         _serverSocket.BeginAccept(AcceptCallback, null);
         Console.WriteLine("Server setup complete");
         Console.WriteLine("Listening on port: " + _port);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
コード例 #57
0
ファイル: ServerDynamic.cs プロジェクト: waffle-iron/nequeo
        /// <summary>
        /// Start accepting socket connections.
        /// </summary>
        private void StartAccept()
        {
            try
            {
                // Clear last error.
                ClearLastError();

                do
                {
                    // Set the event to nonsignaled state.
                    _connAvailable.Reset();

                    // Do not allow any more clients
                    // if maximum is reached.
                    if (_clientCount < _maxNumClients)
                    {
                        // Set the event to nonsignaled state.
                        _connAccept.Reset();

                        // Create a new client connection handler for the current
                        // tcp client attempting to connect to the server. Creates
                        // a new channel from the client to the server.
                        _socket.BeginAccept(new AsyncCallback(CreateServerContext), _socket);

                        // Wait until a connection is made and processed before continuing.
                        _connAccept.WaitOne();
                    }
                    else
                    {
                        // Blocks the current thread until a
                        // connection becomes available.
                        _connAvailable.WaitOne();
                    }
                } while (true);
            }
            catch (Exception ex)
            {
                // Stop listening.
                StopListening();

                SetLastError(ex);

                // Trigger the stop listening event.
                StopListeningEvent(ex);
            }
        }
コード例 #58
0
        public void OnClientConnect(IAsyncResult asyn)
        {
            try {
                System.Net.Sockets.Socket workerSocket = mainSocket.EndAccept(asyn);
                Interlocked.Increment(ref clientCount);
                workerSocketList.Add(workerSocket);

                // SendMsgToClient(msg, clientCount - 1);

                UpdateClientList();
                WaitForData(workerSocket, clientCount);
                mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            } catch (ObjectDisposedException) {
                Console.WriteLine("OnClientConnection: Socket has been closed\n");
            } catch (SocketException se) {
                Console.WriteLine(se.Message);
            }
        }
コード例 #59
0
        /// <summary>
        /// 开启服务端socket监听
        /// </summary>
        public static void ServerSocketListing(SocketConnectConfig sktconfig)
        {
            DicSockectConnection.Clear();
            _cancellationTocken = new CancellationTokenSource();
            if (sktconfig == null)
            {
                sktconfig = new SocketConnectConfig()
                {
                    ServerSocket = ServerSocketListenner
                }
            }
            ;
            else if (sktconfig.ServerSocket == null)
            {
                sktconfig.ServerSocket = ServerSocketListenner;
            }
            Sktconfig = sktconfig;
            try
            {
                if (SocketConnectionClient.SocketClient != null && SocketConnectionClient.SocketClient.Connected)
                {
                    SocketConnectionClient.SocketClientConnection.Disconnect();
                }

                SocketConnectionClient.ClientSocketStarting(connection =>
                {
                    ServerSocketClient = (SocketConnection)connection;
                    SendCurrentConnectionCount();
                }     //监听打开后,发送当前上位机的连接数目信息
                                                            );

                ServerSocketListenner.IOControl(IOControlCode.KeepAliveValues, KeepAlive(1, Sktconfig.KeepAliveTime ?? 2 * 60 * 1000, Sktconfig.KeepAliveTime ?? 2 * 60 * 1000), null); //设置心跳检测
                ServerSocketListenner.BeginAccept(AcceptCallback, sktconfig);
                Task.Run(() =>                                                                                                                                                          //解决主线程直接调用报错
                {
                    ShowMsg($"socket server listening at {ServerSocketListenner.LocalEndPoint}...");
                });
            }
            catch (SocketException se)
            {
                SocketException(ServerSocketListenner, se);
            }
        }
コード例 #60
0
        public void StartSocket()
        {
            int listeningPort = Utils.getUnusedPort(PORT_START, PORT_END);

            // Establish the local endpoint for the socket.
            // The DNS name of the computer
            // running the listener is "IPv4"
            IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, listeningPort);

            // Create a TCP/IP socket.
            listener = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(64);        // max 64 listening ports

                while (_isRunning)
                {
                    // Set the event to nonsignaled state.
                    allDone.Reset();

                    // Start an asynchronous socket to listen for connections.
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        listener);

                    // Wait until a connection is made before continuing.
                    allDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            listener.Close();
        }