예제 #1
1
    public bool CreateTcpServer(string ip, int listenPort)
    {
        _port = listenPort;
        _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        foreach (IPAddress address in Dns.GetHostEntry(ip).AddressList)
        {
            try
            {
                IPAddress hostIP = address;
                IPEndPoint ipe = new IPEndPoint(address, _port);

                _listener.Bind(ipe);
                _listener.Listen(_maxConnections);
                _listener.BeginAccept(new System.AsyncCallback(ListenTcpClient), _listener);

                break;

            }
            catch (System.Exception)
            {
                return false;
            }
        }

        return true;
    }
예제 #2
0
        private void OnAcceptConnection(IAsyncResult asyncResult)
        {
            try
            {
                if (_serverSocket == null)
                {
                    return;
                }

                var server = (Socket)asyncResult.AsyncState;
                var client = server.EndAccept(asyncResult);

                var newPlayer = new Player(client);

                if (!Sahara.GetServer().GetGameManager().GetPlayerManager().TryAddPlayer(newPlayer))
                {
                    _logManager.Log("Error trying to add player.", LogType.Error);
                }
            }
            catch (SocketException socketException)
            {
                var method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                _logManager.Log("Error in " + method + ": " + socketException.Message, LogType.Error);
                _logManager.Log(socketException.StackTrace, LogType.Error);
            }
            finally
            {
                _serverSocket?.BeginAccept(OnAcceptConnection, _serverSocket);
            }
        }
예제 #3
0
        public bool Start()
        {
            try
            {
                Trace.TraceInformation("SimpleHttpServer.Start()");
                _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                _listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                var localEp = new IPEndPoint(0, Port);

                _listener.Bind(localEp);
                _listener.Listen(100);

                _listener?.BeginAccept(AcceptClient, _listener);
                return(true);
            }
            catch (Exception ex)
            {
                if (ex is Win32Exception native)
                {
                    if (native.NativeErrorCode == 13 && SystemInfo.Platform == Platform.Linux && Port < 1024)
                    {
                        Trace.TraceError("Ports below 1024 are considered 'privileged' and can only be bound to with an equally privileged user (read: root).");
                    }
                }
                Trace.TraceError(ex.Message);
                _listener?.Close();
                _listener?.Dispose();
                return(false);
            }
        }
예제 #4
0
파일: server.cs 프로젝트: mono/gert
	Server ()
	{
		_listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		_listener.Bind (new IPEndPoint (IPAddress.Loopback, 10000));
		_listener.Listen (10);
		_listener.BeginAccept (new AsyncCallback (OnAccept), _listener);
	}
예제 #5
0
        public void ReceiveTimesOut_Throws()
        {
            using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    int port = localSocket.BindToAnonymousPort(IPAddress.IPv6Loopback);
                    localSocket.Listen(1);
                    IAsyncResult localAsync = localSocket.BeginAccept(null, null);

                    remoteSocket.Connect(IPAddress.IPv6Loopback, port);

                    Socket acceptedSocket = localSocket.EndAccept(localAsync);
                    acceptedSocket.ReceiveTimeout = 100;

                    SocketException sockEx = Assert.Throws<SocketException>(() =>
                   {
                       acceptedSocket.Receive(new byte[1]);
                   });

                    Assert.Equal(SocketError.TimedOut, sockEx.SocketErrorCode);
                    Assert.True(acceptedSocket.Connected);
                }
            }
        }
예제 #6
0
 public void StartListening(int port) 
 { 
     try { // Resolve local name to get IP address 
         IPHostEntry entry = Dns.Resolve(Dns.GetHostName()); 
         IPAddress ip = entry.AddressList[0]; 
         // Create an end-point for local IP and port 
         IPEndPoint ep = new IPEndPoint(ip, port); 
         if(isLogging)
             TraceLog.myWriter.WriteLine ("Address: " + ep.Address.ToString() +" : " + ep.Port.ToString(),"StartListening"); 
         EventLog.WriteEntry("MMFCache Async Listener","Listener started on IP: " + 
                 ip.ToString() + " and Port: " +port.ToString()+ "."); 
         // Create our socket for listening 
         s = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
         // Bind and listen with a queue of 100 
         s.Bind(ep); 
         s.Listen(100); 
         // Setup our delegates for performing callbacks 
         acceptCallback = new AsyncCallback(AcceptCallback); 
         receiveCallback = new AsyncCallback(ReceiveCallback); 
         sendCallback = new AsyncCallback(SendCallback); 
         // Set the "Accept" process in motion 
         s.BeginAccept(acceptCallback, s); 
     } 
     catch(SocketException e) { 
         Console.Write("SocketException: "+ e.Message); 
     } 
 } 
예제 #7
0
    public static void StartListening()
    {
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

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

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

            while (true)
            {
                AllDone.Reset();
                listener.BeginAccept(AcceptCallback, listener);
                AllDone.WaitOne();
            }
        }
        catch (Exception e)
        {
            throw;
        }
    }
	public static void StartListening()
	{
		// Data buffer for incoming data.     
		// Establish the local endpoint for the socket.     
		// The DNS name of the computer     
		// running the listener is "host.contoso.com".     
		//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
		//IPAddress ipAddress = ipHostInfo.AddressList[0];
		IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
		IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
		// 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 (!stop)
			{
				// Set the event to nonsignaled state.     
				allDone.Reset();
				// Start an asynchronous socket to listen for connections.     
				LogMgr.Log("Waiting for a connection...");
				listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
				// Wait until a connection is made before continuing.     
				allDone.WaitOne();
			}
		}
		catch (Exception e)
		{
			LogMgr.LogError(e);
		}

	}
예제 #9
0
    /// <summary>
    /// Socket Initialization Place Any Other Code Before the Socket Initialization
    /// </summary>
    private void Start()
    {
        limits.x = -4;
        limits.y =  8;
        limits.z =  4;

        AudioManager.Instance.PlaySound(EAudioPlayType.BGM, audioClip);

        if (toPototatoeFountainOrNotToPotatoeFountain)
        { StartCoroutine(POTATOFOUNTAIN()); } 

        if (socketBehaviour == ESocketBehaviour.Server)
        {
            clients = new List<Socket>();

            buffer = new byte[1024];

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

            IPEndPoint parsedIP = new IPEndPoint(IPAddress.Parse(IP), port);

            mySocket.Bind(parsedIP);
            mySocket.Listen(100);
            mySocket.BeginAccept( new AsyncCallback(AcceptCallback), null );

            return;
        }

        if (socketBehaviour == ESocketBehaviour.Client)
        {
            buffer = new byte[1];
        }
    }
예제 #10
0
        private void OnClientAccept(IAsyncResult asyncResult)
        {
            if (m_Socket == null)
            {
                return; // Server Shutting Down
            }
            var socket = m_Socket.EndAccept(asyncResult);

            if (socket == null)
            {
                return; // Server Shutting Down
            }
            var client = new TelnetClient(socket)
            {
                OnClientTerminated = OnClientTerminated
            };

            lock (m_Lock)
            {
                Clients.Add(client);
            }

            OnClientConnected(client);
            m_Socket?.BeginAccept(OnClientAccept, null);
        }
예제 #11
0
파일: TcpClient.cs 프로젝트: arahis/Swiper
 public void BeginAccept(int port)
 {
     Ipep = new IPEndPoint(IPAddress.Any, port);
     ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     ServerSocket.Bind(Ipep);
     ServerSocket.Listen(1);
     ServerSocket.BeginAccept(OnAccept, ServerSocket);
 }
예제 #12
0
        public void BeginAccept_NotListening_Throws_InvalidOperation()
        {
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));

                Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null));
            }
        }
예제 #13
0
 public void CreateServer()
 {
     MySocket = new Socket(AddressFamily.InterNetwork,
                           SocketType.Stream,
                           ProtocolType.IP);
     MySocket.Bind(new IPEndPoint(IPAddress.Any, NetworkConnector.Port));
     MySocket.Listen(10);
     MySocket.BeginAccept(new System.AsyncCallback(this.OnSocketConnect),
                          null);
 }
예제 #14
0
 void createServer(int port)
 {
     _acceptServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     _acceptServer.Bind(new IPEndPoint(IPAddress.Loopback, port));
     _acceptServer.Listen(0);
     _acceptServer.BeginAccept(ar => {
         var socket = (Socket)ar.AsyncState;
         _clientServer = socket.EndAccept(ar);
     }, _acceptServer);
 }
예제 #15
0
        public SocketTestServerAPM(int numConnections, int receiveBufferSize, EndPoint localEndPoint) 
        {
            _log = VerboseTestLogging.GetInstance();
            _receiveBufferSize = receiveBufferSize;

            socket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(localEndPoint);
            socket.Listen(numConnections);
            
            socket.BeginAccept(OnAccept, null);
        }
	static void AppDomainMethod () {
		Console.WriteLine ("two");
		var socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		IPEndPoint ep = new IPEndPoint(IPAddress.Any, 9999);
		socket.Bind (ep);
		socket.Listen (10);
		socket.BeginAccept ( delegate {
			Console.WriteLine ("Delegate should not be called!");
			Environment.Exit (1);
		}, socket);
	}
    public void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024*1024];

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

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

        CalculationManager cm = new CalculationManager();

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

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

                // Start an asynchronous socket to listen for connections.
                Console.WriteLine("Waiting for a connection... port : " + 12000);

                listener.BeginAccept(
                    new AsyncCallback(AcceptCallback),
                    listener);

                allDone.WaitOne();

                // Wait until a connection is made before continuing.

                Console.WriteLine("-------------------------------------");
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

    }
        private void RunnerDoWork()
        {
            Trace.TraceInformation("SocketCommandLineServer.RunnerDoWork()");
            try
            {
                if (_listener == null)
                {
                    return;
                }
                _listener.Listen(100);
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
                return;
            }
            Trace.TraceInformation("SocketCommandLineServer started.");
            _clientAccepted.Set();
            while (!_cancelRunner && (_listener != null) && _listener.IsBound)
            {
                try
                {
                    if (_clientAccepted.WaitOne(1000, false)) // use this version for Windows 2000 compatibility
                    {
                        _clientAccepted.Reset();
                        _listener?.BeginAccept(AcceptClient, null);
                    }
                }
                catch (SocketException ex)
                {
                    if ((ex.SocketErrorCode != SocketError.Interrupted) &&
                        (ex.SocketErrorCode != SocketError.ConnectionReset))
                    {
                        Trace.TraceError(ex.Message);
                    }
                    break;
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.Message);
                    break;
                }
            }

            Disconnect();
            _runnerCanceled = true;
            Trace.TraceInformation("SocketCommandLineServer terminated.");
        }
예제 #19
0
    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // The DNS name of the computer

        IPAddress ipAddress = IPAddress.Parse("188.26.11.125"); //ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 80);

        // 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.
                Console.WriteLine("Waiting for a connection...");
                listener.BeginAccept(
                    new AsyncCallback(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();

    }
예제 #20
0
    public bool Host(int port)
    {
        socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

        try
        {
            socket.Bind(new IPEndPoint(IP,kPort));
            socket.Listen(kHostConnectionBacklog);
            socket.BeginAccept(new System.AsyncCallback(OnClientConnect),socket);
        }
        catch(System.Exception e)
        {

            socket = null;
            return false;
        }
        return true;
    }
예제 #21
0
    public bool CreateTcpServer(string address, int listenPort)
    {
        _port = listenPort;
        _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(address), listenPort);
            _listener.Bind(ipe);
            _listener.Listen(_maxConnections);
            _listener.BeginAccept(new System.AsyncCallback(ListenTcpClient), _listener);
        }
        catch (System.Exception)
        {
            return false;
        }

        return true;
    }
    public alta_class_net(int nPortListen = 339)
    {
        // Determine the IPAddress of this machine
        List<IPAddress> aryLocalAddr = new List<IPAddress>();
        string strHostName = "";

        try
        {
            // NOTE: DNS lookups are nice and all but quite time consuming.
            strHostName = Dns.GetHostName();
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            foreach (IPAddress ip in ipEntry.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    aryLocalAddr.Add(ip);
                }

            }
        }
        catch (Exception ex)
        {
            Debug.Log(string.Format("Error trying to get local address {0} ", ex.Message));
            aryLocalAddr.Clear();
            aryLocalAddr.Add(IPAddress.Loopback);
        }

        // Verify we got an IP address. Tell the user if we did
        if (aryLocalAddr == null || aryLocalAddr.Count < 1)
        {
            Debug.LogWarning("Unable to get local address");
            return;
        }
        Debug.Log(string.Format("Listening on : [{0}] {1}:{2}", strHostName, aryLocalAddr[0], nPortListen));

        // Create the listener socket in this machines IP address
        listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener.Bind(new IPEndPoint(aryLocalAddr[0], nPortListen));
        //listener.Bind( new IPEndPoint( IPAddress.Loopback, 399 ) );	// For use with localhost 127.0.0.1
        listener.Listen(10);
        // Setup a callback to be notified of connection requests
        listener.BeginAccept(new AsyncCallback(this.OnConnectRequest), listener);
    }
예제 #23
0
        public void SocketSendTimeout_Send_Success()
        {
            using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    int port = localSocket.BindToAnonymousPort(IPAddress.IPv6Loopback);
                    localSocket.Listen(1);
                    IAsyncResult localAsync = localSocket.BeginAccept(null, null);

                    remoteSocket.Connect(IPAddress.IPv6Loopback, port);

                    Socket acceptedSocket = localSocket.EndAccept(localAsync);
                    acceptedSocket.SendTimeout = 100;

                    // Note that Send almost never times out because it only has to copy the data to the native buffer.
                    int bytes = acceptedSocket.Send(new byte[100]);
                    Assert.Equal(100, bytes);
                    Assert.True(acceptedSocket.Connected);
                }
            }
        }
예제 #24
0
	public static void StartListening() 
	{
		// Establish the local endpoint for the socket.
		// The DNS name of the computer
		// running the listener is "host.contoso.com".
		IPHostEntry ipHostInfo = Dns.GetHostEntry("127.0.0.1");
		IPAddress ipAddress = ipHostInfo.AddressList[0];
		IPEndPoint localEndPoint = new IPEndPoint(ipAddress, TestServer.PORT);
		
		// 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.
				//Console.WriteLine("Waiting for a connection...");
				Debug.Log("S: Waiting for a connection.. \n");
				listener.BeginAccept( 
				                     new AsyncCallback(AcceptCallback),
				                     listener );
				
				// Wait until a connection is made before continuing.
				allDone.WaitOne();
			}
			
		} catch (Exception e) {
			Console.WriteLine(e.ToString());
		}
	}
예제 #25
0
    public void StartListening()
    {
        byte[] bytes = new Byte[1024];
        IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 9050);
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            listener.Bind(ipEnd);
            listener.Listen(100);
            while (true)
            {
                allDone.Reset();
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                allDone.WaitOne();

            }
        }
        catch (Exception ex)
        {

        }

    }
예제 #26
0
 private static Task <Socket> AcceptAsync(Socket socket)
 {
     return(Task.Factory.FromAsync((cb, state) => socket.BeginAccept(cb, state), ar => socket.EndAccept(ar), null));
 }
예제 #27
0
 private void BeginAccept()
 {
     _socket.BeginAccept(OnAccept, null);
 }
예제 #28
0
파일: Program.cs 프로젝트: eugbus/Banjo
        static void Main(string[] args)
        {
            SetConsoleCtrlHandler(new EventHandler(ConsoleCtrlHandler), true);

            if (args.Length == 0)
            {
                Console.WriteLine("USAGE: BANJO [-ip 0.0.0.0] [-p 23] [-pw 1234] [-c \"cmd.exe\"] [-a \"parameters\"] [-w \"C:\\\"] [-log \"C:\\log.txt\"]");
                Environment.Exit(0);
            }

            Log("Starting Banjo...");

            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 23);

            try
            {
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "/ip":
                    case "-ip":
                        endPoint.Address = IPAddress.Parse(args[++i]);
                        break;

                    case "/p":
                    case "-p":
                        endPoint.Port = int.Parse(args[++i]);
                        break;

                    case "/pw":
                    case "-pw":
                        password = args[++i];
                        break;

                    case "/c":
                    case "-c":
                        consoleCommand = args[++i];
                        break;

                    case "/a":
                    case "-a":
                        consoleArguments = args[++i];
                        break;

                    case "/w":
                    case "-w":
                        consoleWorkingDirectory = args[++i];
                        break;

                    case "/log":
                    case "-log":
                        string filename = args[++i];
                        int    j        = 1;
                        while (File.Exists(filename))
                        {
                            filename = string.Format("{0}({1}){2}", Path.Combine(Path.GetDirectoryName(args[i]), Path.GetFileNameWithoutExtension(args[i])), j++, Path.GetExtension(args[i]));
                        }
                        if (args[i] != filename)
                        {
                            File.Move(args[i], filename);
                        }
                        logWriter = new StreamWriter(args[i]);
                        break;

                    default:
                        Log("ERROR: Invalid parameter.");
                        Exit(-1);
                        break;
                    }
                }
            }
            catch (IndexOutOfRangeException)
            {
                Log("ERROR: Missing argument.");
                Exit(-1);
            }
            catch (FormatException)
            {
                Log("ERROR: Invalid IP address.");
                Exit(-1);
            }
            catch (Exception ex)
            {
                Log(ex.ToString());
            }

            try
            {
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Bind(endPoint);
                serverSocket.Listen(0);
                serverSocket.BeginAccept(new AsyncCallback(ListenAsyncCallback), serverSocket);
                Log("Banjo listening.");
            }
            catch (Exception ex)
            {
                Log(ex.Message);
                Exit(-1);
            }

            try
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo(consoleCommand)
                {
                    CreateNoWindow         = true,
                    ErrorDialog            = false,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    WorkingDirectory       = consoleWorkingDirectory,
                    Arguments = consoleArguments
                };
                process = new Process()
                {
                    StartInfo = processStartInfo
                };
                process.Start();
                StartConsoleProcessReader(process.StandardOutput);
                StartConsoleProcessReader(process.StandardError);

                Version version = Assembly.GetExecutingAssembly().GetName().Version;
                Console.Title = string.Format("Banjo v{1}.{2} rev {3} - ({0})", consoleCommand, version.Major, version.Minor, version.Revision);

                Log("'{0}' started.", consoleCommand);
                Log("Parameters '{0}'.", consoleArguments);
                Log("Working Directory '{0}'.", consoleWorkingDirectory);

                if (logWriter != null)
                {
                    logFlushTimer.Elapsed  += LogFlushTimer_Elapsed;
                    logFlushTimer.AutoReset = true;
                    logFlushTimer.Start();
                }

                while (!process.HasExited)
                {
                    if (Console.KeyAvailable)
                    {
                        process.StandardInput.Write(Console.ReadKey().KeyChar);
                    }
                }
            }
            catch (Exception ex)
            {
                Log(ex.ToString());
            }

            Log("Process terminated with exit code ({0}).", process.ExitCode);
            Exit(0);
        }
예제 #29
0
        public void Update()
        {
            //异步接收客户端
            if (accept)
            {
                try
                {
                    acceptAsync = server.BeginAccept(null, null);
                    accept      = false;
                }
                catch (Exception) { }
            }
            if (acceptAsync.IsCompleted)
            {
                try
                {
                    Socket socket = server.EndAccept(acceptAsync);
                    clients.Add(new Client(true, socket));
                    OnConnected?.Invoke(socket);
                }
                catch (Exception) { }
                finally { accept = true; }
            }

            //异步接收消息
            foreach (Client client in clients)
            {
                if (!client.Connected) //不接受断开连接的消息
                {
                    continue;
                }
                Socket socket = client.Socket;

                if (socket.Available > 0)
                {
                    try
                    {
                        NetworkSerializer.UnpackTCPMessage(socket, out ushort cmd1, out ushort cmd2, out byte[] data);
                        int key = NetworkSerializer.EnumToKey(cmd1, cmd2);

                        if (events.ContainsKey(key))
                        {
                            events[key](socket, data);
                        }
                    }
                    catch (Exception ex)
                    {
                        socket.Close();
                        client.Connected = false;
                        OnDisconnected?.Invoke(ex.Message, socket);
                    }
                }
            }

            //异步发送消息
            while (messages.Count > 0)
            {
                Message message = messages.Dequeue();
                Socket  socket  = message.Socket;

                bool pass = false;
                foreach (Client client in clients)
                {
                    if (client.Socket == socket && client.Connected) //存在该客户端并且该客户端激活
                    {
                        pass = true;
                        break;
                    }
                }
                if (!pass)
                {
                    continue;
                }

                try
                {
                    message.Send();
                }
                catch (Exception ex)
                {
                    socket.Close();
                    //禁用该Socket
                    foreach (Client client in clients)
                    {
                        if (client.Socket == socket)
                        {
                            client.Connected = false;
                        }
                    }
                    OnDisconnected?.Invoke(ex.Message, socket);
                    break;
                }
            }
        }
예제 #30
0
        private void tryBind(Socket listener, ServerConfiguration configuration)
        {
            IPEndPoint localEndPoint = new IPEndPoint(configuration.ipAddresses[0], configuration.port);

                listener.Bind(localEndPoint);
                listener.Listen(configuration.backLog);
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
        }
 protected override IAsyncResult BeginConnectStream(AsyncCallback callback, object state)
 {
     return(wifiListener.BeginAccept(callback, state));
 }
예제 #32
0
    private bool Host(int port)
    {
        mSocketDebug.DebugLog("lServer: Hosting on " + IP + " : " + port);

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

        mSocket.ReceiveBufferSize = 8192;

        try
        {
            mSocket.Bind (new IPEndPoint (IP, port));
            mSocket.Listen (kHostConnectionBacklog);
            mSocket.BeginAccept (new System.AsyncCallback (OnClientConnect), mSocket);
        }
        catch (System.Exception e)
        {
            mSocketDebug.DebugLogError("lServer: Exception when attempting to host (" + IP + " : " + port + "): " + e);
            mSocket = null;
            return false;
        }

        return true;
    }
예제 #33
0
 private void _asyncAccepter()
 {
     m_Listener.BeginAccept(_accepterCallback, null);
 }
예제 #34
0
        void ServerMode()
        {
            m_ActiveRecv           = true;
            timerReconnect.Enabled = false;

            string strSrcIP = textBoxSrcIp.Text;
            int    sSrcPort = Int32.Parse(textBoxSrcPort.Text);
            string strDstIP = textBoxDstIp.Text;
            int    sDstPort = Int32.Parse(textBoxDstPort.Text);

            try
            {
                localSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                localSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                var local = new System.Net.IPEndPoint(IPAddress.Parse(strSrcIP), sSrcPort);
                localSocket.Bind(local);
                localSocket.Listen(100);

                m_thread = new Thread(new ThreadStart(() =>
                {
                    while (m_ActiveRecv == true)
                    {
                        // Set the event to nonsignaled state.
                        allDone.Reset();

                        localSocket.BeginAccept(
                            new AsyncCallback(AcceptCallback),
                            localSocket);

                        try
                        {
                            Invoke(new ListAddDelegate(SendStart));
                        }
                        catch (Exception)
                        {
                        }

                        // Wait until a connection is made before continuing.
                        allDone.WaitOne(1000);
                    }
                    if (m_ns != null)
                    {
                        m_ns.Close();
                    }
                    if (localSocket != null)
                    {
                        localSocket.Close();
                    }
                    if (state != null)
                    {
                        if (state.workSocket != null)
                        {
                            state.workSocket.Close();
                        }
                    }
                }));

                m_thread.Start();
                listBox1.Items.Add("Accept開始");

                buttonConnect.Enabled    = false;
                buttonDisconnect.Enabled = true;
            }
            catch (Exception)
            {
                listBox1.Items.Add("接続失敗");
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
                listBox1.TopIndex      = listBox1.SelectedIndex;
                if (m_ns != null)
                {
                    m_ns.Close();
                }
                if (localSocket != null)
                {
                    localSocket.Close();
                }
                if (state != null)
                {
                    if (state.workSocket != null)
                    {
                        state.workSocket.Shutdown(SocketShutdown.Both);
                        state.workSocket.Close();
                    }
                }
            }
        }
예제 #35
0
 internal void getConnection(Socket sock)
 {
     allDone.Reset();
     sock.BeginAccept(new AsyncCallback(acceptCallback), sock);
     allDone.WaitOne();
 }
예제 #36
0
    public void StartListening(int port=11211) {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

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

        // Bind the socket to the local endpoint and listen for incoming connections.
        try {
            // Create a TCP/IP socket.
            listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp );

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

            running = true;
            while (running) {
                // 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(ThreadAbortException e) {
            //listener.OnGetData -= GetData;
            //listener.StopListening();
            //thread.Join();

        } catch (Exception e) {
            Debug.Log(e.ToString());
        }
    }
예제 #37
0
 private void DualModeConnect_BeginAccept_Helper(IPAddress listenOn, IPAddress connectTo)
 {
     using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp))
     {
         int port = serverSocket.BindToAnonymousPort(listenOn);
         serverSocket.Listen(1);
         IAsyncResult async = serverSocket.BeginAccept(null, null);
         SocketClient client = new SocketClient(serverSocket, connectTo, port);
         Socket clientSocket = serverSocket.EndAccept(async);
         Assert.True(clientSocket.Connected);
         Assert.True(clientSocket.DualMode);
         Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily);
         Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address);
     }
 }
예제 #38
0
        static void Main(string[] args)
        {
            Logger.LogFile = $".{Path.DirectorySeparatorChar}HackLinks.log";
            Logger.Archive = $".{Path.DirectorySeparatorChar}Archive";

            Logger.Info("HackLinks Server is starting up.");

            bool   showHelp        = false;
            bool   rebuildDB       = false;
            bool   writeConfig     = false;
            bool   overwriteConfig = false;
            string writeConfigPath = null;

            //Set Defaults and create config object
            ConfigUtil.ConfigData configData = new ConfigUtil.ConfigData();
            configData.MySQLServer   = "127.0.0.1";
            configData.Port          = 27015;
            configData.Database      = "hacklinks";
            configData.UserID        = "root";
            configData.Password      = "";
            configData.SaveFrequency = 300; // 300 seconds, 60 seconds * 5, 5 minutes.

            bool passSet = true;

            //Handle Args
            OptionSet options = new OptionSet()
            {
                { "s|server=", "the MySQL {SERVER} to use (default: \"127.0.0.1\").", v => configData.MySQLServer = v },
                { "d|database=", "the {DATABASE} to use (default: \"hacklinks\").", v => configData.Database = v },
                { "f|save-frequency=", "the time to wait, in seconds, between writing the game state to the database (default: 300).", v => configData.SaveFrequency = int.Parse(v) },
                { "u|user="******"the {USERNAME} to connect with (default: \"root\").", v => configData.UserID = v },
                { "p|password:"******"set the {PASSWORD} to connect with (default: None) or prompt for a password.", v => { passSet = v != null;  configData.Password = v; } },
                { "P|port=",
                  "set the {PORT} to open the server on (default: 27015).",
                  v =>
                  {
                      int result;
                      if (int.TryParse(v, out result))
                      {
                          configData.Port = result;
                      }
                      else
                      {
                          Logger.Warning("Invalid Port Specified: \"{0}\". Using Default Port.", v);
                      }
                  } },
                { "c|config:",
                  "load settings from {CONFIG} file (default: No) or from default config file \"serverconfig.conf\".\n" +
                  "If the file doesn't exist it will be created with the the final values when the server runs unless the {-o/--overwrite-config} flag specifies a file instead.",
                  v =>
                  {
                      //Use given path, Existing path if it exists, or default if not.
                      string readConfigPath = v ?? "serverconfig.conf";

                      //If we aren't overwritting or if we are but the path is unset
                      if (!overwriteConfig || overwriteConfig && writeConfigPath == null)
                      {
                          writeConfigPath = readConfigPath;
                      }

                      //Loadconfig returns true if the file was loaded. So we should write the config if it's not
                      writeConfig = !ConfigUtil.LoadConfig(readConfigPath, configData);
                  } },
                { "o|overwrite-config:",
                  "force the {CONFIG} file to be overwritten with the final values when the server runs.\n" +
                  "You can optionally specify the config file to be written here.",
                  v =>
                  {
                      //If config path is specified use that instead
                      writeConfigPath = v ?? writeConfigPath ?? "serverconfig.conf";

                      overwriteConfig = true;
                  } },
                { "r|rebuild", "rebuild the database (WARNING: this will delete all data).", v => rebuildDB = v != null },
                { "h|help", "show this message and exit.", v => showHelp = v != null },
            };

            try
            {
                options.Parse(args);

                if (showHelp) // If help requested then show help and exit
                {
                    Console.WriteLine("Usage: HackLinks Server.exe [OPTIONS]");
                    Console.WriteLine("Starts the HackLinks Server.");
                    Console.WriteLine();

                    // output the options
                    Console.WriteLine("Options:");
                    options.WriteOptionDescriptions(Console.Out);

                    return;
                }

                //We write our config here as we likely don't want to save the prompted password
                if (overwriteConfig || writeConfig)
                {
                    ConfigUtil.SaveConfig(writeConfigPath, configData);
                }

                //Check if password is null and prompt if it is
                //Done here to avoid asking for password when other options are going to fail anyway or help should be displayed.
                if (!passSet)
                {
                    configData.Password = GetPassword();
                }
            } catch (OptionException e)
            {
                //One of our options failed. Output the message
                Logger.Exception(e);
                return;
            }

            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, configData.Port);

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

            Server.Instance.Initalize(configData);
            //If we're going to rebuild the DB we need to do it before data is loaded but after the server has the mysql config
            if (rebuildDB)
            {
                Server.Instance.DatabaseLink.RebuildDatabase();
            }
            Server.Instance.StartServer();

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

                var stopWatch = Stopwatch.StartNew();
                while (true)
                {
                    if (recieving == false)
                    {
                        listener.BeginAccept(
                            new AsyncCallback(AcceptCallback),
                            listener);
                        Logger.Status($"Server ready, listening on {localEndPoint}");
                        recieving = true;
                    }

                    double dT = stopWatch.ElapsedMilliseconds / (double)1000;
                    stopWatch.Restart();
                    Server.Instance.MainLoop(dT);

                    if (DateTimeOffset.UtcNow.ToUnixTimeSeconds() - previousUploadTime > configData.SaveFrequency)
                    {
                        previousUploadTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                        Server.Instance.SaveDatabase();
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Exception(e);
            }

            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
예제 #39
0
        public NewChat(bool isHost, string name, string Ip = null)
        {
            InitializeComponent();

            var timer = new DispatcherTimer();

            timer.Interval = new TimeSpan(0, 0, 2);
            timer.Tick    += ((sender, e) =>
            {
                ChatBox.Height += 10;

                if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
                {
                    scrollViewer.ScrollToEnd();
                }
            });
            timer.Start();

            if (isHost)
            {
                _isHost  = true;
                nickname = $"{name}(Host)";

                socket.Bind(new IPEndPoint(IPAddress.Any, 8005));
                socket.Listen(0);

                ChatBox.Text = "Server Started...\nWaiting for incoming client connections...";

                socket.BeginAccept(AcceptCallBack, null);
            }
            else
            {
                _isHost  = false;
                nickname = name;

                try
                {
                    socket.Connect(new IPEndPoint(IPAddress.Parse(Ip), 8005));
                    ChatBox.Text += $"Welcome to the chat room {nickname}!";

                    Task.Factory.StartNew(() =>
                    {
                        while (true)
                        {
                            try
                            {
                                var buffer       = new byte[256];
                                var receivedData = socket.Receive(buffer, 0, buffer.Length, 0);

                                Array.Resize(ref buffer, receivedData);

                                Dispatcher.Invoke(() =>
                                {
                                    ChatBox.Text += $"\n{DateTime.Now.ToShortTimeString()} {Encoding.Default.GetString(buffer)}";
                                });
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    Application.Current.Shutdown();
                }
            }
        }
        public void Start(Configuration config, int port)
        {
            _config       = config;
            _shareOverLan = config.ShareOverLan;
            _authUser     = config.AuthUser;

            var localPort = port == 0 ? _config.LocalPort : port;

            if (CheckIfPortInUse(localPort))
            {
                throw new Exception(string.Format(I18NUtil.GetAppStringValue(@"PortInUse"), localPort));
            }

            try
            {
                //TODO:UDP socket
                // Create a TCP/IP socket.
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                var localEndPoint = new IPEndPoint(_shareOverLan ? IPAddress.Any : IPAddress.Loopback, localPort);
                // Bind the socket to the local endpoint and listen for incoming connections.
                _socket.Bind(localEndPoint);
                _socket.Listen(1024);

                // IPv6
                if (Global.OSSupportsLocalIPv6)
                {
                    try
                    {
                        _socketV6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                        _socketV6.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    }
                    catch
                    {
                        _socketV6 = null;
                    }
                    var localEndPointV6 = new IPEndPoint(_shareOverLan ? IPAddress.IPv6Any : IPAddress.IPv6Loopback, localPort);
                    if (_socketV6 != null)
                    {
                        _socketV6.Bind(localEndPointV6);
                        _socketV6.Listen(1024);
                    }
                }
                else
                {
                    _socketV6 = null;
                }

                // Start an asynchronous socket to listen for connections.
                Console.WriteLine($@"ShadowsocksR started on port {localPort}");
                _socket.BeginAccept(AcceptCallback, _socket);
                _socketV6?.BeginAccept(AcceptCallback, _socketV6);
            }
            catch (SocketException e)
            {
                Logging.LogUsefulException(e);
                if (_socket != null)
                {
                    _socket.Close();
                    _socket = null;
                }
                if (_socketV6 != null)
                {
                    _socketV6.Close();
                    _socketV6 = null;
                }
                throw;
            }
        }
예제 #41
0
        public void StartListening()
        {
            Console.WriteLine("Starting USG network service...");
            try
            {
                WaitForClient();
            }
            catch (SocketException ex)
            {
                Console.WriteLine($"Broadcast socket unavailable: {ex.Message}");
                Environment.Exit(1);
            }

            var newsock =
                new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                ReceiveTimeout = _SOCKET_TIMEOUT,
                SendTimeout    = _SOCKET_TIMEOUT
            };

            try
            {
                // Accept connection.
                Console.WriteLine($"Waiting client at {_localIp}:{_PORT_NUMBER}...");
                newsock.Bind(new IPEndPoint(IPAddress.Any, _PORT_NUMBER));
                newsock.Listen(10);
                AutoResetEvent accepted = new AutoResetEvent(false);
                newsock.BeginAccept(ar =>
                {
                    if (ar == null || newsock == null)
                    {
                        return;
                    }
                    try
                    {
                        _client = newsock.EndAccept(ar);
                        ar.AsyncWaitHandle.WaitOne();
                        Console.WriteLine(
                            $"Client accepted. Remote: {((IPEndPoint) _client.RemoteEndPoint).Address}:" +
                            $"{((IPEndPoint) _client.RemoteEndPoint).Port}");
                        accepted.Set();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Accept exception: {e.Message}\n{e.ToString()}");
                    }
                }, newsock);

                if (!accepted.WaitOne(_SOCKET_TIMEOUT))
                {
                    throw new TimeoutException("Error: Client connection accept timeout.");
                }

                Console.WriteLine("Main routine...");

                // Maintain commands.
                while (IsClientConnected)
                {
                    var command = ReceiveString();
                    // If we didn't get any command for socket receive timeout, we close the connection.
                    if (command == null)
                    {
                        Console.WriteLine("Connection timeout.");
                        break;
                    }

                    _commandHandler.HandleCommand(command);
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("Socket exception: " + e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception: {e.Message}\n{e.Source}");
            }
            finally
            {
                newsock?.Close();
                newsock = null;
                if (IsClientConnected)
                {
                    Console.WriteLine($"Disconnecting client {((IPEndPoint)_client.RemoteEndPoint).Address}");
                    _client.Shutdown(SocketShutdown.Both);
                    _client.Close();
                    _client = null;
                }
                Console.WriteLine("Socket client closed.");
            }
        }
    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Port on which to listen
        int port = 8001;

        // 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
        {
            foreach (IPAddress ip in Dns.Resolve(Dns.GetHostName()).AddressList)
            {
                Console.WriteLine("Listening on {0}:{1}",
                    ip, port);
            }
            listener.Bind(new IPEndPoint(IPAddress.Any, port));
            listener.Listen(100);

            while (true)
            {
                // 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());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();
    }
        public SocketListener(IPEndPoint endpoint, SocketListenerMode mode)
        {
            // offset port - shutting down a socket and releasing it takes time, so if we
            // keep using the same port, the retry loop below always kicks and slows the
            // tests

            endpoint.Port += _portOffset;
            if (++_portOffset == PortRange)
            {
                _portOffset = 0;
            }

            // note
            // listen backlog 0 is equivalent to 1, backlog -1 means "system queue size"
            //
            // on Windows, if the queue is full, further connections are refused (and client throws)
            // but on Linux... it's different http://veithen.io/2014/01/01/how-tcp-backlog-works-in-linux.html

            // non-Windows: just don't listen = connection refused
            // Windows is more tricky, see below
            if (!OS.IsWindows && mode == SocketListenerMode.ConnectionRefused)
            {
                return;
            }

            _listener = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // retry loop
            var i = 0;

            while (true)
            {
                try
                {
                    _listener.Bind(endpoint);
                    break;
                }
                catch
                {
                    Thread.Sleep(500);
                    if (i++ == 10)
                    {
                        throw;
                    }
                }
            }

            switch (mode)
            {
            case SocketListenerMode.Default:
            case SocketListenerMode.ConnectionRefused:
                // listen, backlog 1 connection in the queue, never accept it
                // so all subsequent requests will be refused
                _listener.Listen(1);
                _socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                _socket.Connect(endpoint);
                break;

            case SocketListenerMode.AcceptOnce:
                // listen, accept first connection, backlog others
                // so they are not accepted, but not refused
                _listener.Listen(-1);
                _listener.BeginAccept(AcceptCallback, _listener);
                break;
            }
        }
예제 #44
0
    public bool Host(int port)
    {
        Debug.Log ("Hosting on port " + port);

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

        try
        {
            socket.Bind (new IPEndPoint (IP, port));
            socket.Listen (kHostConnectionBacklog);
            socket.BeginAccept (new System.AsyncCallback (OnClientConnect), socket);
        }
        catch (System.Exception e)
        {
            Debug.LogError ("Exception when attempting to host (" + port + "): " + e);

            socket = null;

            return false;
        }

        return true;
    }
예제 #45
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="callback"></param>
 /// <param name="state"></param>
 /// <returns></returns>
 public override IAsyncResult BeginAccept(AsyncCallback callback, object state)
 {
     return(socket.BeginAccept(callback, state));
 }
예제 #46
0
 public void StartAccepting()
 {
     _logger.Trace("Waiting for incoming connection..");
     _server?.BeginAccept(AcceptCallback, null);
 }
예제 #47
0
 public void Start(IPEndPoint endPoint)
 {
     _listener.Bind(endPoint);
     _listener.Listen(10);
     _listener.BeginAccept(AcceptClient, _listener);
 }
예제 #48
0
        /// <summary>
        /// Open a listener socket and wait for connections
        /// </summary>
        void StartListening(ref Socket ListeningSocket)
        {
            // Note: Do not catch exceptions until we reach the main
            // listening loop, because <c>StartThread</c> should
            // intercept initialization exceptions.

            // Establish the local endpoint for the socket (only on localhost)
            IPAddress lb = (BindAddress == null)
                ? (UseIPv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback)
                : BindAddress;
            IPEndPoint localEndPoint = new IPEndPoint(lb, this.LocalPort);

            // Create a TCP/IP socket
            AddressFamily af = UseIPv6 ? AddressFamily.InterNetworkV6 :
                AddressFamily.InterNetwork;
            ListeningSocket = new Socket(af, SocketType.Stream,
                ProtocolType.Tcp);

            log.Info("Listening to incoming IPv" +
                (UseIPv6 ? "6" : "4") + " connections on port " + LocalPort);

            if (BeforeBindListeningSocket != null)
                BeforeBindListeningSocket(ListeningSocket);

            // Bind the socket to the local endpoint and listen for incoming
            // connections.
            ListeningSocket.Bind(localEndPoint);
            ListeningSocket.Listen(1000);

            // Notify that the listening thread is up and running
            IsListening = true;
            InitListenFinished.Set();

            // Main listening loop starts now
            try
            {
                while (!IsShuttingDown)
                {
#if DEBUG_ACCEPT_CONNECTION
                    log.Debug("Reset signal");
#endif

                    ListenThreadSwitch.Reset();
                    if (IsShuttingDown)
                        break;

#if DEBUG_ACCEPT_CONNECTION
                    log.Debug("BeginAccept (before)");
#endif

                    ListeningSocket.BeginAccept(
                        new AsyncCallback(AcceptCallback), ListeningSocket);

#if DEBUG_ACCEPT_CONNECTION
                    log.Debug("Wait signal");
#endif

                    // Wait until a connection is made before continuing
                    ListenThreadSwitch.WaitOne();

#if DEBUG_ACCEPT_CONNECTION
                    log.Debug("Received signal");
#endif
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }
            finally
            {
                log.Debug("Stopped listening on port " + LocalPort);
            }
        }
예제 #49
0
 /// <summary>
 /// Ожидание получения данных
 /// </summary>
 public void Accept()
 {
     _socket.BeginAccept(new AsyncCallback(AcceptCallback), null);
 }
예제 #50
0
        public void StartListening()
        {
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), Port);

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

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

                var host = Dns.GetHostEntry(Dns.GetHostName());

                for (int cwidth = Console.WindowWidth; cwidth - 2 > 0; cwidth--)
                {
                    Console.Write("*");
                }
                Console.WriteLine("*");

                Console.ForegroundColor = ConsoleColor.Red;
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        Console.WriteLine("Use this ip/port if ASteambot **IS** running on the same machine as the server :");
                        Console.WriteLine("IP : " + ip + " PORT : " + Port);
                    }
                }

                Console.WriteLine("Use this ip/port if ASteambot **IS NOT** running on the same machine as the server :");
                Console.WriteLine("IP : " + new System.Net.WebClient().DownloadString("https://api.ipify.org").Replace("\n", "") + " PORT : " + Port);
                Console.ForegroundColor = ConsoleColor.White;


                Console.WriteLine("Example (in ASteambot_Core.cfg) : ");
                Console.WriteLine("   sm_asteambot_server_ip \"XXX.XXX.XX.XX\" ");
                Console.WriteLine("   sm_asteambot_server_port \"" + Port + "\" ");

                for (int cwidth = Console.WindowWidth; cwidth - 2 > 0; cwidth--)
                {
                    Console.Write("*");
                }
                Console.WriteLine("*");

                Running = true;
                while (Running)
                {
                    allDone.Reset();

                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

                    while (!allDone.WaitOne(3000) && Running)
                    {
                        if (!Running)
                        {
                            break;
                        }
                    }
                }
            }
            catch (SocketException e)
            {
                Program.PrintErrorMessage("Error while creating socket ! It may be because of the port being already usued! Use another TCP port number.");
                Program.PrintErrorMessage(e.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
예제 #51
0
        // this is the call back function,
        private void OnClientConnect(IAsyncResult ar)
        {
            try
            {
                if (_mainSocket == null)
                {
                    return;
                }

                // Here we complete/end the BeginAccept asynchronous call
                // by calling EndAccept() - Which returns the reference
                // to a new Socket object.
                var workerSocket = _mainSocket.EndAccept(ar);

                // Validate If client should connect.
                var ipAddress = ((IPEndPoint)workerSocket.RemoteEndPoint).Address;
                var ipString  = ipAddress.ToString();

                var isAllowed = false;
                switch (_settings.UserSettingsModel.FilterSelection)
                {
                case FilteringSelection.Specific:
                    foreach (var source in _settings.UserSettingsModel.IpAddressList)
                    {
                        if (string.Compare(ipString, source, StringComparison.Ordinal) == 0)
                        {
                            isAllowed = true;
                        }
                    }

                    break;

                case FilteringSelection.Range:
                    var settings = _settings.UserSettingsModel;
                    isAllowed = RangeChecker.AddressInRange(ipString, settings.BaseIp, settings.LastOctetMax);
                    break;

                default:
                    isAllowed = true;
                    break;
                }

                if (Equals(ipAddress, IPAddress.Loopback))
                {
                    isAllowed = true;
                }

                if (!isAllowed)
                {
                    workerSocket.Send(
                        Encoding.UTF8.GetBytes(new SocketMessage(Constants.NotAllowed, string.Empty).ToJsonString()));
                    workerSocket.Close();
                    _logger.Debug($"Client {ipString} was force disconnected IP was not in the allowed addresses");
                    _mainSocket.BeginAccept(OnClientConnect, null);
                    return;
                }

                var connectionId = IdGenerator.GetUniqueKey();

                if (!_availableWorkerSockets.TryAdd(connectionId, workerSocket))
                {
                    return;
                }

                // Inform the the Protocol Handler that a new Client has been connected, prepare for handshake.
                _hub.Publish(new ClientConnectedEvent(ipAddress, connectionId));

                // Let the worker Socket do the further processing
                // for the just connected client.
                WaitForData(workerSocket, connectionId);
            }
            catch (ObjectDisposedException)
            {
                _logger.Debug("OnClientConnection: Socket has been closed");
            }
            catch (SocketException se)
            {
                _logger.Debug(se, "On client connect");
            }
            catch (Exception ex)
            {
                _logger.Debug($"OnClientConnect Exception : {ex.Message}");
            }
            finally
            {
                try
                {
                    // Since the main Socket is now free, it can go back and
                    // wait for the other clients who are attempting to connect
                    _mainSocket?.BeginAccept(OnClientConnect, null);
                }
                catch (Exception e)
                {
                    _logger.Debug($"OnClientConnect Exception : {e.Message}");
                }
            }
        }
예제 #52
0
 private void BeginAccept()
 {
     listenSocket.BeginAccept(new AsyncCallback(AsyncAcceptCallBack), listenSocket);
 }
        public void Start()
        {
            if (_isStarted)
            {
                return;
            }
            _isStarted = true;
            try
            {
                Log(LogLevel.Info, "Begin starting Communication Service");
                _bufferSize = 8192;

                _receiveQueue = new Queue();
                _sendQueue    = new Queue();
                _socketList   = new List <Socket>();

                Log(LogLevel.Info, "Begin socket server start          port " + _serverPort);
                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, _serverPort);
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.Bind(ipEndPoint);
                _socket.Listen(4);
                Log(LogLevel.Info, "End socket server start            port " + _serverPort);

                Log(LogLevel.Info, "Begin opening Multicast Socket at          " + _multicastIPAddress + ":" + _multicastPort);
                _multicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                _multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 5);
                _multicastSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                EndPoint multicastEndPoint = new IPEndPoint(IPAddress.Any, _multicastPort);
                _multicastSocket.Bind(multicastEndPoint);
                Log(LogLevel.Info, "Setting multicast ReceiveBufferSize to     " + _bufferSize);
                _multicastSocket.ReceiveBufferSize = _bufferSize;

                MulticastOption multicastOption = new MulticastOption(IPAddress.Parse(_multicastIPAddress), IPAddress.Any);
                _multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOption);
                Log(LogLevel.Info, "End opening Multicast Socket at            " + _multicastIPAddress + ":" + _multicastPort);

                Log(LogLevel.Info, "Begin starting Worker Threads");
                _receiveWorkerThread      = new Thread(ProcessReceiveQueue);
                _receiveWorkerThread.Name = "ProcessReceiveQueue";
                _receiveWorkerThread.Start();

                _sendWorkerThread      = new Thread(ProcessSendQueue);
                _sendWorkerThread.Name = "ProcessSendQueue";
                _sendWorkerThread.Start();

                _listenWorkerMulticastThread      = new Thread(StartListeningMulticast);
                _listenWorkerMulticastThread.Name = "StartListeningMulticast";
                _listenWorkerMulticastThread.Start();


                Log(LogLevel.Info, "End starting Worker Threads");
                _socket.BeginAccept(new AsyncCallback(OnClientConnect), null);
                Log(LogLevel.Info, "End starting Communication Service");
            }
            catch (Exception exception)
            {
                LogException(exception);
                Stop();
                throw; // exception;
            }
        }
예제 #54
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation());
            LoggingService.LogInfo("Running on {0}", RuntimeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();
            sectionTimings ["PlatformInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            GettextCatalog.Initialize();
            sectionTimings ["GettextInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            if (!Platform.IsWindows)
            {
                // The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
                // Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
                // to be too late to prevent the MEF composition and the static registrar from
                // failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
                ResolveMSBuildAssemblies();
            }

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            // explicit GLib type system initialization for GLib < 2.36 before any other type system access
            GLib.GType.Init();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize();
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);

            sectionTimings["GtkInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();
            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Runtime.LoadAssemblyFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            sectionTimings["XwtInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            sectionTimings["DispatchInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            // Initialize Roslyn's synchronization context
            RoslynServices.RoslynService.Initialize();

            sectionTimings["RoslynInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            AddinManager.AddinLoadError += OnAddinError;

            startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            sectionTimings ["RuntimeInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            bool restartRequested = PropertyService.Get("MonoDevelop.Core.RestartRequested", false);

            startupInfo.Restarted = restartRequested;
            PropertyService.Set("MonoDevelop.Core.RestartRequested", false);

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            sectionTimings["ThemeInitialized"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            ProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            sectionTimings["PlatformInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");

            CheckFileWatcher();

            sectionTimings["FileWatcherInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                sectionTimings ["ImageInitialization"] = startupSectionTimer.ElapsedMilliseconds;
                startupSectionTimer.Restart();

                // If we display an error dialog before the main workbench window on OS X then a second application menu is created
                // which is then replaced with a second empty Apple menu.
                // XBC #33699
                Counters.Initialization.Trace("Initializing IdeApp");

                hideWelcomePage = options.NoStartWindow || startupInfo.HasFiles || IdeApp.Preferences.StartupBehaviour.Value != OnStartupBehaviour.ShowStartWindow;
                IdeApp.Initialize(monitor, hideWelcomePage);
                sectionTimings ["AppInitialization"] = startupSectionTimer.ElapsedMilliseconds;
                startupSectionTimer.Restart();

                if (errorsList.Count > 0)
                {
                    using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog(errorsList.ToArray(), false)) {
                        if (!dlg.Run())
                        {
                            return(1);
                        }
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                RecentFile openedProject = null;
                if (IdeApp.Preferences.StartupBehaviour.Value == OnStartupBehaviour.LoadPreviousSolution && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    openedProject = DesktopService.RecentFiles.MostRecentlyUsedProject;
                    if (openedProject != null)
                    {
                        var metadata = GetOpenWorkspaceOnStartupMetadata();
                        IdeApp.Workspace.OpenWorkspaceItem(openedProject.FileName, true, true, metadata).ContinueWith(t => IdeApp.OpenFiles(startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext());
                        startupInfo.OpenedRecentProject = true;
                    }
                }
                if (openedProject == null)
                {
                    IdeApp.OpenFiles(startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata());
                    startupInfo.OpenedFiles = startupInfo.HasFiles;
                }

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                message = message + "\n\n" + error.Message;
                MessageService.ShowFatalError(message, null, error);

                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog(errorsList.ToArray(), true))
                    dlg.Run();
            }

            errorsList = null;
            AddinManager.AddinLoadError -= OnAddinError;

            sectionTimings["BasicInitializationCompleted"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            sectionTimings["SocketInitialization"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            initialized = true;
            MessageService.RootWindow    = IdeApp.Workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow);

            sectionTimings["WindowOpened"] = startupSectionTimer.ElapsedMilliseconds;
            startupSectionTimer.Restart();

            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();

            // This call is important so the current event loop is run before we run the main loop.
            // On Mac, the OpenDocuments event gets handled here, so we need to get the timeout
            // it queues before the OnIdle event so we can start opening a solution before
            // we show the main window.
            DispatchService.RunPendingEvents();

            sectionTimings ["PumpEventLoop"] = startupSectionTimer.ElapsedMilliseconds;
            startupTimer.Stop();
            startupSectionTimer.Stop();

            // Need to start this timer because we don't know yet if we've been asked to open a solution from the file manager.
            timeToCodeTimer.Start();
            ttcMetadata = new TimeToCodeMetadata {
                StartupTime = startupTimer.ElapsedMilliseconds
            };

            // Start this timer to limit the time to decide if the app was opened by a file manager
            IdeApp.StartFMOpenTimer(FMOpenTimerExpired);
            IdeApp.Workspace.FirstWorkspaceItemOpened += CompleteSolutionTimeToCode;
            IdeApp.Workbench.DocumentOpened           += CompleteFileTimeToCode;

            CreateStartupMetadata(startupInfo, sectionTimings);

            GLib.Idle.Add(OnIdle);
            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
예제 #55
0
        public void MyAsyncCallback(IAsyncResult ar)
        {
            //初始化一个SOCKET,用于其它客户端的连接
            Socket server1 = (Socket)ar.AsyncState;
            Socket Client  = server1.EndAccept(ar);

            //获取客户端的IP和端口
            string ip = Client.RemoteEndPoint.ToString();

            //当客户端终止连接时
            TextBox1SetText(ip + "登录");
            //将要发送给连接上来的客户端的提示字符串

            User   user       = (User)Personfactory.getPerson("User", ip, new Point(0, 0), 10);
            Button userbutton = new Button();

            userbutton.Enabled = true;
            userbutton.Visible = true;
            add(userbutton);
            string strDateLine = "Login";

            Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine);
            //将提示信息发送给客户端
            Client.Send(byteDateLine, byteDateLine.Length, 0);
            //等待新的客户端连接
            server1.BeginAccept(new AsyncCallback(MyAsyncCallback), server1);
            while (true)
            {
                int recv = 0;
                try
                {
                    recv = Client.Receive(byteDateLine);
                }
                catch
                {
                    break;
                }

                string         stringdata = Encoding.ASCII.GetString(byteDateLine, 0, recv);
                DateTimeOffset now        = DateTimeOffset.Now;
                //获取客户端的IP和端口
                if (stringdata == "STOP" || stringdata == "")
                {
                    //当客户端终止连接时
                    TextBox1SetText(ip + "已从服务器断开");
                    break;
                }
                else if (stringdata.Trim() == "GET")
                {
                    byte[] re = Encoding.Default.GetBytes(user.Speack());
                    Client.Send(re, re.Length, 0);
                }
                else if (stringdata.Trim() == "w")
                {
                    Client.Send(Encoding.Default.GetBytes(user.w()));
                }
                else if (stringdata.Trim() == "a")
                {
                    Client.Send(Encoding.Default.GetBytes(user.a()));
                }
                else if (stringdata.Trim() == "s")
                {
                    Client.Send(Encoding.Default.GetBytes(user.s()));
                }
                else if (stringdata.Trim() == "d")
                {
                    Client.Send(Encoding.Default.GetBytes(user.d()));
                }

                buttonset(userbutton, user);
                ////显示客户端发送过来的信息
                //TextBox1SetText(ip + "    " + now.ToString("G") + "     " + stringdata + "\r\n");
            }
        }
예제 #56
0
    static void Main(string[] args)
    {
        if (args.Length != 1) // Test for correct # of args
          throw new ArgumentException("Parameters: <Port>");

        int servPort = Int32.Parse(args[0]);

        // Create a Socket to accept client connections
        Socket servSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                                 ProtocolType.Tcp);

        servSock.Bind(new IPEndPoint(IPAddress.Any, servPort));
        servSock.Listen(BACKLOG);

        for (;;) { // Run forever, accepting and servicing connections
          Console.WriteLine("Thread {0} ({1}) - Main(): calling BeginAccept()",
                        Thread.CurrentThread.GetHashCode(),
                        Thread.CurrentThread.ThreadState);

          IAsyncResult result = servSock.BeginAccept(new AsyncCallback(AcceptCallback),
                                                 servSock);
          doOtherStuff();

          // Wait for the EndAccept before issuing a new BeginAccept
          result.AsyncWaitHandle.WaitOne();
        }
    }
예제 #57
0
파일: Network.cs 프로젝트: hhrhzy/mywork
 public void Listen(int Port, int ListeningQueueLength)
 {
     Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         Listener.Bind(new IPEndPoint(IPAddress.Parse("0"), Port));
     }
     catch
     {
         if (OnBindFail != null)
         {
             OnBindFail();
         }
     }
     try
     {
         Listener.Listen(ListeningQueueLength);
         Listener.BeginAccept(new AsyncCallback(AcceptCallBack), Listener);
     }
     catch
     {
         if (OnListenFail != null)
         {
             OnListenFail();
         }
     }
 }
예제 #58
0
        /// <summary>
        /// Called for every new connection request.
        /// </summary>
        /// <param name="ar">The async result containing the server socket</param>
        public void OnConnectRequest(IAsyncResult ar)
        {
            //Init SOCKET
            Socket serverSocket    = (Socket)ar.AsyncState;
            Socket newClientSocket = serverSocket.EndAccept(ar);
            string welcomeMessage  = "Welcome! The Server is Connected!";

            byte[] byteDateLine = System.Text.Encoding.UTF8.GetBytes(welcomeMessage);
            //show message to client and show the connection infos
            string ip = newClientSocket.RemoteEndPoint.ToString();

            _logger(ip + "::connection established:" + DateTime.Now.ToString("G"));
            newClientSocket.Send(byteDateLine, byteDateLine.Length, 0);
            // Buffer messages from the client
            bool          terminated = false;
            MessageBuffer buffer     = new MessageBuffer((string message) => { HandleMetaMessage(newClientSocket, message, out terminated); });

            // Wait for another new client connection
            serverSocket.BeginAccept(new AsyncCallback(OnConnectRequest), serverSocket);
            // Start receiving messages until communication termination
            try
            {
                while (!terminated)
                {
                    // Read the message
                    int    recv       = newClientSocket.Receive(byteDateLine);
                    string stringdata = Encoding.UTF8.GetString(byteDateLine, 0, recv);
                    // Pass message to buffer
                    buffer.SubmitFragment(stringdata);
                }
            }
            catch (SocketException ex)
            {
                try
                {
                    // Log exception
                    _logger(newClientSocket.RemoteEndPoint.ToString() + "::exception:" + ex.Message + ":" + DateTime.Now.ToString("G"));
                    // Try to remove the client
                    bool foundClient = false; ClientType clientType = ClientType.R; int clientID = 0;
                    if (_botClients.Values.Contains(newClientSocket))
                    {
                        foundClient = true; clientType = ClientType.R; clientID = _botClients.First(kvp => kvp.Value == newClientSocket).Key;
                    }
                    if (_controlClients.Values.Contains(newClientSocket))
                    {
                        foundClient = true; clientType = ClientType.C; clientID = _controlClients.First(kvp => kvp.Value == newClientSocket).Key;
                    }
                    if (_iStationClients.Values.Contains(newClientSocket))
                    {
                        foundClient = true; clientType = ClientType.I; clientID = _iStationClients.First(kvp => kvp.Value == newClientSocket).Key;
                    }
                    if (_oStationClients.Values.Contains(newClientSocket))
                    {
                        foundClient = true; clientType = ClientType.O; clientID = _oStationClients.First(kvp => kvp.Value == newClientSocket).Key;
                    }
                    if (foundClient)
                    {
                        RemoveDeadClient(clientType, clientID, newClientSocket);
                    }
                }
                catch (ObjectDisposedException) { _logger(ip + "::exception:" + ex.Message + ":" + DateTime.Now.ToString("G")); }
            }
        }
예제 #59
0
        private void DualModeConnect_BeginAccept_Helper(IPAddress listenOn, IPAddress connectTo)
        {
            using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                int port = serverSocket.BindToAnonymousPort(listenOn);
                serverSocket.Listen(1);
                IAsyncResult async = serverSocket.BeginAccept(null, null);
                SocketClient client = new SocketClient(_log, serverSocket, connectTo, port);

                // Due to the nondeterministic nature of calling dispose on a Socket that is doing
                // an EndAccept operation, we expect two types of exceptions to happen.
                Socket clientSocket;
                try
                {
                    clientSocket = serverSocket.EndAccept(async);
                    Assert.True(clientSocket.Connected);
                    AssertDualModeEnabled(clientSocket, listenOn);
                    Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily);
                    if (connectTo == IPAddress.Loopback)
                    {
                        Assert.Contains(((IPEndPoint)clientSocket.LocalEndPoint).Address, ValidIPv6Loopbacks);
                    }
                    else
                    {
                        Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address);
                    }
                    Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address);
                }
                catch (ObjectDisposedException) { }
                catch (SocketException) { }

                Assert.True(
                    client.WaitHandle.WaitOne(Configuration.PassingTestTimeout),
                    "Timed out while waiting for connection");

                if ( client.Error != SocketError.Success)
                {
                    throw new SocketException((int)client.Error);
                }
            }
        }
예제 #60
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            SetupTheme();

            var args = options.RemainingArgs.ToArray();

            Gtk.Application.Init(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Assembly.LoadFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();

            //default to Windows IME on Windows
            if (Platform.IsWindows && Mono.TextEditor.GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = Mono.TextEditor.GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    Mono.TextEditor.GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            InternalLog.Initialize();
            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(new GtkSynchronizationContext());
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);


            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();

            Counters.Initialization.Trace("Initializing theme and splash window");

            DefaultTheme = Gtk.Settings.Default.ThemeName;
            string theme = IdeApp.Preferences.UserInterfaceTheme;

            if (string.IsNullOrEmpty(theme))
            {
                theme = DefaultTheme;
            }
            ValidateGtkTheme(ref theme);
            if (theme != DefaultTheme)
            {
                Gtk.Settings.Default.ThemeName = theme;
            }


            //don't show the splash screen on the Mac, so instead we get the expected "Dock bounce" effect
            //this also enables the Mac platform service to subscribe to open document events before the GUI loop starts.
            if (Platform.IsMac)
            {
                options.NoSplash = true;
            }

            IProgressMonitor monitor = null;

            if (!options.NoSplash)
            {
                try {
                    monitor = new SplashScreenForm();
                    ((SplashScreenForm)monitor).ShowAll();
                } catch (Exception ex) {
                    LoggingService.LogError("Failed to create splash screen", ex);
                }
            }
            if (monitor == null)
            {
                monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();
            }

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");
            string version = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor;

            if (Assembly.GetEntryAssembly().GetName().Version.Build != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Build;
            }
            if (Assembly.GetEntryAssembly().GetName().Version.Revision != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Revision;
            }

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                if (errorsList.Count > 0)
                {
                    if (monitor is SplashScreenForm)
                    {
                        ((SplashScreenForm)monitor).Hide();
                    }
                    AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false);
                    if (!dlg.Run())
                    {
                        return(1);
                    }
                    if (monitor is SplashScreenForm)
                    {
                        ((SplashScreenForm)monitor).Show();
                    }
                    reportedFailures = errorsList.Count;
                }

                // no alternative for Application.ThreadException?
                // Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                // Load requested files
                Counters.Initialization.Trace("Opening Files");
                IdeApp.OpenFiles(startupInfo.RequestedFileList);

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                LoggingService.LogFatalError(null, error);
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString(
                                                                          "MonoDevelop failed to start. The following error has been reported: {0}",
                                                                          error.Message
                                                                          ));
                MessageService.ShowException(error, message);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true);
                dlg.Run();
            }

            errorsList = null;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow = IdeApp.Workbench.RootWindow;
            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();
            IdeApp.Run();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();
            InstrumentationService.Stop();
            AddinManager.AddinLoadError -= OnAddinError;

            return(0);
        }