BeginAcceptTcpClient() public method

public BeginAcceptTcpClient ( AsyncCallback callback, object state ) : IAsyncResult
callback AsyncCallback
state object
return IAsyncResult
 public void initializeListener()
 {
     listener = new TcpListener(new IPEndPoint(IPAddress.Any, Multiplayer.PORT));
     listener.AllowNatTraversal(true);
     listener.Start();
     listener.BeginAcceptTcpClient(AcceptTcpConnectionCallback, listener);
 }
Example #2
0
        public MockBroker()
        {
            listener = new TcpListener(Dns.GetHostAddresses("localhost")[0], brokerPort);
            listener.Start();

            listener.BeginAcceptTcpClient(ConnectAccept, null);
        }
 public Server()
 {
     config = new INIReader(System.IO.File.ReadAllLines("config.ini"));
     chat = new ServerChat();
     instance = this;
     vehicleController = new ServerVehicleController();
     api = new ServerApi(this);
     gamemodeManager = new GamemodeManager(api);
     gamemodeManager.loadFromFile("gamemodes/" + config.getString("gamemode"));
     server = new TcpListener(IPAddress.Any, config.getInt("game_port"));
     server.Start();
     server.BeginAcceptTcpClient(onIncomingConnection, null);
     playerpool = new List<ServerPlayer>();
     Timer timer = new Timer();
     timer.Elapsed += onBroadcastTimer;
     timer.Interval = config.getInt("broadcast_interval");
     timer.Enabled = true;
     timer.Start();
     UDPStartPort = config.getInt("udp_start_port");
     Timer timer_slow = new Timer();
     timer_slow.Elapsed += timer_slow_Elapsed;
     timer_slow.Interval = config.getInt("slow_interval");
     timer_slow.Enabled = true;
     timer_slow.Start();
     http_server = new HTTPServer();
     Console.WriteLine("Started game server on port " + config.getInt("game_port").ToString());
     Console.WriteLine("Started http server on port " + config.getInt("http_port").ToString());
 }
Example #4
0
File: Coob.cs Project: Wroud/Coob
        public Coob(CoobOptions options)
        {
            this.Options = options;
            MessageQueue = new ConcurrentQueue<Packet.Base>();
            PacketParsers = new Dictionary<int, PacketParserDel>();
            Clients = new Dictionary<ulong, Client>();
            World = new World(options.WorldSeed);

            PacketParsers.Add((int)CSPacketIDs.EntityUpdate, Packet.EntityUpdate.Parse);
            PacketParsers.Add((int)CSPacketIDs.Interact, Packet.Interact.Parse);
            PacketParsers.Add((int)CSPacketIDs.Shoot, Packet.Shoot.Parse);
            PacketParsers.Add((int)CSPacketIDs.ClientChatMessage, Packet.ChatMessage.Parse);
            PacketParsers.Add((int)CSPacketIDs.ChunkDiscovered, Packet.UpdateChunk.Parse);
            PacketParsers.Add((int)CSPacketIDs.SectorDiscovered, Packet.UpdateSector.Parse);
            PacketParsers.Add((int)CSPacketIDs.ClientVersion, Packet.ClientVersion.Parse);

            try
            {
                clientListener = new TcpListener(IPAddress.Any, options.Port);
                clientListener.Start();
                clientListener.BeginAcceptTcpClient(onClientConnect, null);
            }
            catch (SocketException e)
            {
                if (e.ErrorCode == 10048)
                    Log.Error("Something is already running on port " + options.Port + ". Can't start server.");
                else
                    Log.Error("Unknown error occured while trying to start server:\n" + e);

                Log.Display();
                Environment.Exit(1);
            }
        }
Example #5
0
        public void Connect(int localPort, int remotePort, IPAddress remoteAddress)
        {
            IPAddress localhost = Dns.GetHostAddresses("127.0.0.1")[0];
            listener = new TcpListener(localhost, localPort);
            BooleanEventArg arg;
            try
            {
                listener.Start();
            }
            catch (Exception e)
            {
                arg = new BooleanEventArg();
                arg.result = false;
                //localClientConnectedToRemoteServer.Set();
                connected(this, arg);
                return;
            }
            
            listener.BeginAcceptTcpClient(AcceptClient, listener);

            client = new TcpClient();

            Thread.Sleep(1000);
            //localClientConnectedToRemoteServer.Reset();
            client.BeginConnect(remoteAddress, remotePort, ServerConnected, client);

            //localClientConnectedToRemoteServer.WaitOne();
        }
Example #6
0
		/// <summary>
		/// Start server and begin accepting clients
		/// </summary>
		public static void Start()
		{
			futureMoves = new Queue<FutureMove>();
			clientsPlaying = new List<Connection>();
			clientUpdate = new List<Connection>();
			clientAI = new List<Connection>();
			clientPlayers = new List<Connection>();
			clientsAll = new List<Connection>();
			updateTimer.Elapsed += new ElapsedEventHandler(UpdateTick);
			updateTimer.AutoReset = false;
			if (listener != null) listener.Stop();
			listener = TcpListener.Create(Program.port);
			listener.Start();
			allDone = new ManualResetEvent(false);
			try
			{
				while (true)
				{
					allDone.Reset();
					listener.BeginAcceptTcpClient(new AsyncCallback(AcceptTcpClient), listener);
					allDone.WaitOne();
				}
			}
			catch (ThreadAbortException)
			{
				listener.Stop();
			}
		}
Example #7
0
 /*
  * Listens for clients connection requests
  */
 public void Connect()
 {
     object state = new object();
     tcp = new TcpListener(IPAddress.Any, 4550);
     tcp.Start();
     tcp.BeginAcceptTcpClient(onAccept, tcp);
 }
 public SimpleRendezvousServer()
 {
     mListener = new TcpListener(new IPEndPoint(IPAddress.Any, 0));
     mListener.Start();
     //mListener.BeginAcceptSocket(OnAccept, null);
     mListener.BeginAcceptTcpClient(OnAccept, null);
 }
        public void Initialize()
        {
            tcpServer = new TcpListener(IPAddress.Any, 1901);

            tcpServer.BeginAcceptTcpClient()

            sender = new UdpClient();

            sender.DontFragment = true;

            sender.JoinMulticastGroup(remoteEndPoint.Address);

            listener = new UdpClient();

            listener.ExclusiveAddressUse = false;

            listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            listener.ExclusiveAddressUse = false;

            listener.Client.Bind(anyEndPoint);

            listener.DontFragment = true;

            listener.JoinMulticastGroup(remoteEndPoint.Address);

            listener.BeginReceive(ReceiveCallback, null);
        }
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="iAddress">ローカルのIPアドレスを指定します。</param>
        /// <param name="iPort">待受けに使用するポート番号を指定します。</param>
        public TcpAcceptor(IPAddress iAddress, int iPort)
        {
            // 引数のチェック
            if (iAddress == null)
            {
                var nm = MethodBase.GetCurrentMethod().GetParameters()[0].Name;
                throw new ArgumentNullException(nm);
            }
            else if (iPort <= 0)
            {
                var nm = MethodBase.GetCurrentMethod().GetParameters()[1].Name;
                throw new ArgumentOutOfRangeException(nm, "不正なポート番号が指定されました。");
            }

            try
            {
                // 待受け開始
                var listener = new TcpListener(iAddress, iPort);
                listener.Start();
                listener.BeginAcceptTcpClient(new AsyncCallback(this.AcceptCallback), null);

                this.tcpListener = listener;
            }
            catch (Exception)
            {
                // そのまま呼び出し元にスローする。
                throw;
            }
        }
Example #11
0
        public static void Main(string[] args)
        {
            Action<object> cw = Console.WriteLine;
              cw("* any");
              cw(IPAddress.Any);
              cw(IPAddress.IPv6Any);
              cw("* loopback");
              cw(IPAddress.Loopback);
              cw(IPAddress.IPv6Loopback);
              cw("* none");
              cw(IPAddress.None);
              cw(IPAddress.IPv6None);
              cw("* bc4"); //trivia: there is no bc6, only multicast
              cw(IPAddress.Broadcast);

              TcpListener l = new TcpListener(IPAddress.Any, 7896);
              l.Start();
              l.BeginAcceptTcpClient(ar => {
            var c = l.EndAcceptTcpClient(ar);
            l.Stop();
            //var s = new StreamWriter(c.GetStream());
            //s.WriteLine("test writer : needed");
            //s.Flush();
            var bs = System.Text.Encoding.UTF8.GetBytes("test direct : not needed");
            c.GetStream().Write(bs, 0, bs.Length);
            c.Close();
              }, l);

              //start client
              var q = new TcpClient("localhost", 7896);
              var qs = new StreamReader(q.GetStream());
              Console.WriteLine(qs.ReadLine());
              // l.Stop();
        }
Example #12
0
        private void OnConnect(IAsyncResult ar)
        {
            SOCK.TcpClient newClient = null;
            try
            {
                newClient = m_tcpListener.EndAcceptTcpClient(ar);
            }
            catch (Exception)
            {
            }

            if (null != newClient)
            {
                System.Net.IPEndPoint newEp = (System.Net.IPEndPoint)newClient.Client.RemoteEndPoint;

                m_Settings.WriteMessageToLog(
                    LogMessageType.Information + 1,
                    string.Format(CultureInfo.CurrentUICulture, "Client {0}:{1} connected.", newEp.Address, newEp.Port)
                    );

                SipProxyServer sps = new SipProxyServer(newClient, m_Settings);
                sps.PipeDead += Proxy_PipeDead;
                m_ClientConnections.Add(newEp, sps);
            }

            m_tcpListener.BeginAcceptTcpClient(OnConnect, null);
        }
Example #13
0
        public void Start(string hostName, int port)
        {
            if (_listenerThread == null)
            {
                _port = port;

                #region Listen / Async Accept

                try
                {
                    _listener = new TcpListener(IPAddress.Any, _port);
                    _listener.Start();
                    _listener.BeginAcceptTcpClient(TcpClientConnectCallback, _listener);
                    Console.WriteLine("Listening on {0}", _listener.LocalEndpoint);
                }
                catch
                {
                    if (_listener != null)
                    {
                        _listener.Stop();
                        _listener = null;
                    }
                    throw;
                }

                #endregion

                _listenerThread = new Thread(ListenerThread);
                _frameEvent.Reset();
                _clientConnectedEvent.Reset();
                _listenerThreadRunning = true;
                _listenerThread.Start();
            }
        }
        public void StartServer()
        {
            if (m_SourceForm == null)
            {
                m_SynchronizingObject = m_SourceForm;
            }

            //* Find the IPV4 address of this computer
            string LocalComputerName = System.Net.Dns.GetHostName(); //* same as My.Computer.Name

            System.Net.IPAddress localAddr = GetIPv4Address(LocalComputerName);

            if (localAddr == null)
            {
                localAddr = System.Net.IPAddress.Parse("127.0.0.1");
            }

            try
            {
                server = new TcpListener(localAddr, m_TCPPort);
                server.Start();
                server.BeginAcceptTcpClient(ConnectionAccepted, server);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
        }
Example #15
0
 private void StartListener(IPEndPoint endPoint)
 {
     _listener = new TcpListener(endPoint);
     _listener.Start(5);
     _log.WriteLine("Server {0} listening", endPoint.Address.ToString());
     _listener.BeginAcceptTcpClient(OnAccept, null);
 }
 static void StartListening()
 {
     while (!Server.shouldShutdown)
     {
         try
         {
             listener = new TcpListener(System.Net.IPAddress.Any, Configuration.PORT);
             listener.Start();
             IAsyncResult ar = listener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), listener);
             break;
         }
         catch (SocketException E)
         {
             Console.WriteLine("e1");
             Server.Log(E, LogTypesEnum.error);
             break;
         }
         catch (Exception E)
         {
             Console.WriteLine("e2");
             Server.Log(E, LogTypesEnum.error);
             continue;
         }
     }
 }
        public void StartListening()
        {
            listener = new TcpListener(IPAddress.Any,port);
            listener.Start(50);
            try
            {
                for (; ; )
                {
                    //set the event to nonsignaled state.
                    allDone.Reset();

                    Console.WriteLine("Waiting for a connection...");

                    listener.BeginAcceptTcpClient(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();
        }
Example #18
0
 /// <summary>
 /// Metoda uruchamiaj¹ca workera i rozpoczynaj¹ca nas³uch na odpowiednim IP i porcie
 /// </summary>
 public override void Run()
 {
     TcpListener listener = null;
     try
     {
         listener = new TcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["EncryptEndpoint"].IPEndpoint);
         listener.ExclusiveAddressUse = false;
         listener.Start();
     }
     catch (SocketException)
     {
         Trace.Write("Encrypting server could not start.", "Error");
         return;
     }
         while (true)
         {
             try
             {
                 IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
                 connectionWaitHandle.WaitOne();
             }
             catch
             {
                 continue;
             }
         }
 }
        public override void Run()
        {
            Trace.WriteLine("Starting echo server...", "Information");

            TcpListener listener = null;
            try
            {
                listener = new TcpListener(
                    RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["EchoEndpoint"].IPEndpoint);
                listener.ExclusiveAddressUse = false;
                listener.Start();

                Trace.WriteLine("Started echo server.", "Information");
            }
            catch (SocketException se)
            {
                Trace.Write("Echo server could not start.", "Error");
                return;
            }

            while (true)
            {
                IAsyncResult result =  listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
                _connectionWaitHandle.WaitOne();
            }
        }
Example #20
0
 public TCPServer(int port, Func<Tuple<Socket, Data>, int> receive)
     : base(receive)
 {
     listener = new TcpListener(IPAddress.Any, port);
     listener.Start();
     listener.BeginAcceptTcpClient(ClientConnectedCallback, null);
 }
        public void Start()
        {
            // load the certificate
            // generated with:
            //  makecert.exe -r -pe -n "CN=localhost" -sky exchange -sv server.pvk server.cer
            //  pvk2pfx -pvk server.pvk -spc server.cer -pfx server.pfx
            // TODO: take as parameters
            ServerCertificate = new X509Certificate2("C:\\Users\\mfplab\\Documents\\Visual Studio 2015\\Projects\\TLSIntro01\\cert\\server.pfx", "derp");
            ViewModel.TS_LogMessage("SSL certificate loaded!");

            // start the server
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 5005);
            if (localEndPoint == null)
            {
                ViewModel.TS_SetStatus("ERROR setting up IP end point!");
            }
            else
            {
                TcpListener listener = new TcpListener(localEndPoint);
                if (listener == null)
                {
                    ViewModel.TS_SetStatus("ERROR setting up TcpListener!");
                }
                else
                {
                    listener.Start();
                    ViewModel.TS_SetStatus("TCP listener started");
                    listener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), listener);
                }
            }
        }
Example #22
0
 public override void LoadContent()
 {
     base.LoadContent();
     try
     {
         listener = new TcpListener(IPAddress.Any, Multiplayer.PORT);
         listener.Start();
         listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener);
         buffer = new byte[4096];
         encoder = new ASCIIEncoding();
         if (allLocalIPs.Count == 0)
         {
             myIP = getLocalIP();
             new Thread(getExternalIP).Start();
             Console.WriteLine("Started Multiplayer IP Getter Thread");
         }
         else
             myIP = allLocalIPs[0];
         messages = new List<string>();
         var viewport = ScreenManager.GraphicsDevice.Viewport;
         fullscreen = new Rectangle(0, 0, viewport.Width, viewport.Height);
     }
     catch (Exception ex)
     {
         ScreenManager.RemoveScreen(this);
         ScreenManager.AddScreen(new MainMenu(), ScreenManager.controllingPlayer);
     }
 }
        public override void Run()
        {
            Trace.WriteLine("Starting Telnet Service...", "Information");

            TcpListener listener;
            try
            {
                listener = new TcpListener(
                    RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["TelnetServiceEndpoint"].IPEndpoint) { ExclusiveAddressUse = false };
                listener.Start();

                Trace.WriteLine("Started Telnet Service.", "Information");
            }
            catch (SocketException se)
            {
                Trace.Write("Telnet Service could not start.", "Error");
                return;
            }

            while (true)
            {
                listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
                _connectionWait.WaitOne();
            }
        }
        public void Start()
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, _port);

            _listener = new System.Net.Sockets.TcpListener(ip);
            _listener.Start();
            _listener.BeginAcceptTcpClient(AcceptCallback, _listener);
        }
Example #25
0
 public videoSocketReceiver(int _Port,connectionEstablished _connectionEstablishedHandler)
 {
     connectionEstablishedHandler = _connectionEstablishedHandler;
     port = _Port;
     listener = new TcpListener(IPAddress.Any, port);
     listener.Start();
     listener.BeginAcceptTcpClient(connectionCallback, connectionEstablishedHandler);
 }
Example #26
0
		public void BeginListen(IPAddress address, int port){
			lock(listenLocker){
				IsListening = true;
				Listener = new TcpListener (address, port);
				Listener.Start ();
				Listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptSocketCallback), Listener);
			}
		}
Example #27
0
        public Waiter(int port)
        {
            Users = new List<Client>();

            TcpListener = new TcpListener(port);
            TcpListener.Start();
            TcpListener.BeginAcceptTcpClient(Receive, TcpListener);
        }
Example #28
0
 /// <summary>
 /// 處理 TCP 通訊的類別
 /// </summary>
 public TCPCallBackHandles() {
     AppSettingsSection config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings;
     this.T = new TcpListener(IPAddress.Any, Convert.ToInt16(config.Settings["port"].Value));
     this.T.Start();
     Client.ConsoleWriteTime();
     Console.WriteLine("正版驗證系統開始從 {0} 號通訊埠接聽請求.", config.Settings["port"].Value);
     T.BeginAcceptTcpClient(new AsyncCallback(acceptTCPClientCallback), T);
 }
Example #29
0
		public void Start()
		{
			ClientList = new List<SocketClient>();

			_listener = new TcpListener(IPAddress.Any, Port);
			_listener.Start(10);
			_listener.BeginAcceptTcpClient(OnConnection, null);
		}
Example #30
0
 public TcpListenerSocketService()
 {
     TcpListener server = new TcpListener(new System.Net.IPEndPoint(IPAddress.Any, 12345));
     server.Start(0);
     tcpClientConnected.Reset();
     IAsyncResult result = server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server);
     tcpClientConnected.WaitOne();
 }
Example #31
0
        public ServidorTCP(int puerto)
        {
            listener = new System.Net.Sockets.TcpListener(IPAddress.Any, puerto);

            //Esperar peticiones de conexión
            listener.Start();
            listener.BeginAcceptTcpClient(new AsyncCallback(ComprobarClienteConectado), null);
        }
Example #32
0
 public void Start()
 {
     CloseAllConnections();
     Server = new TcpListener(IPAddress.Any, (int)Settings.Port);
     Server.Start();
     Server.BeginAcceptTcpClient(AcceptClient, null);
     Task.Factory.StartNew(PipeTask);
 }
        private void ThreadProc()
        {
            TcpListener listner = null;
            try
            {
                listner = new TcpListener(IPAddress.Any, _connectionString.Port);
                listner.Start(1);
                Thread clientThread = null;
                do
                {
                    try
                    {
                        //_tcpClientConnected.Reset();
                        IAsyncResult aResult = listner.BeginAcceptTcpClient(null, null);

                        int eventIndex = WaitHandle.WaitAny(new[] { _exit, aResult.AsyncWaitHandle });
                        if (eventIndex == 0) break;

                        //using (TcpClient client = listner.EndAcceptTcpClient(aResult))
                        //{
                        //    aResult.AsyncWaitHandle.Close();
                        //    ReadInLoop(client);
                        //}
                        TcpClient client = listner.EndAcceptTcpClient(aResult);
                        aResult.AsyncWaitHandle.Close();
                        if (_tcpClientConnected != null)
                            _tcpClientConnected.Set();
                        else
                            _tcpClientConnected = new AutoResetEvent(false);
                        if (clientThread != null && clientThread.ThreadState == ThreadState.Running)
                            clientThread.Join();
                        clientThread = new Thread(ReadInLoop) { IsBackground = true };
                        clientThread.Start(client);

                        //_client = listner.EndAcceptTcpClient(aResult);
                        //aResult.AsyncWaitHandle.Close();
                        //listner.Stop();

                        //_client.Client.ReceiveTimeout = ReceiveTimeout;
                        //ReadInLoop();
                    }
                    catch (Exception ex)
                    {
                        _log.WriteError(string.Format("TcpExternalSystemServer: {0}", ex));
                        Thread.Sleep(5000);
                    }
                } while (!_exit.WaitOne(0));
                listner.Stop();
            }
            catch (Exception ex)
            {
                _log.WriteError(string.Format("TcpExternalSystemServer.ThreadProc:\n{0}",ex));
            }
            finally
            {
                listner = null;
            }
        }
Example #34
0
File: Program.cs Project: sbst/code
 public static void DoBeginAcceptTcpClient(TcpListener
     listener)
 {
     tcpClientConnected.Reset();
     listener.BeginAcceptTcpClient(
         new AsyncCallback(DoAcceptTcpClientCallback),
         listener);
     tcpClientConnected.WaitOne();
 }
Example #35
0
        public void Open()
        {
            Console.WriteLine("Waiting for first connection to " + listener.Server.LocalEndPoint);

            Client = listener.AcceptTcpClient();

            // any connection from here on in will auto connect
            listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);
        }
Example #36
0
        private void AcceptPoll()
        {
            /* 接続待機中 */
            if ((accept_task_ar_ != null) && (!accept_task_ar_.IsCompleted))
            {
                return;
            }

            /* 次の接続要求の受付処理を開始 */
            accept_task_ar_ = tcp_listener_.BeginAcceptTcpClient(AcceptTcpClientTaskComplete, tcp_listener_);
        }
        private void ConnectionAccepted(IAsyncResult ar)
        {
            if (!StopThread)
            {
                // Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)
                TcpClient client = server.EndAcceptTcpClient(ar);

                byte[] bytes = new byte[1025];

                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                int i = stream.Read(bytes, 0, bytes.Length);


                string header = "<html xmlns : msxsl = \"urn:schemas-Microsoft - com: xslt\"  meta content=\"en-us\" http-equiv=\"Content-Language\" /> " + "<meta content=\"text/html; charset=utf-16\" http-equiv=\"Content-Type\" /> " + "<meta http-equiv=\"refresh\" content=\"" + m_RefreshTime.ToString() + "\"> ";

                header += "<img src=\"data:image/png;base64,";
                byte[] b = System.Text.ASCIIEncoding.Default.GetBytes(header);
                stream.Write(b, 0, b.Length);

                byte[] Imgbytes = null;
                bmpScreenCapture = new Bitmap(m_SourceForm.Width, m_SourceForm.Height);
                m_SourceForm.Invoke(dcc);
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    bmpScreenCapture.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    Imgbytes = ms.ToArray();
                }

                string s = Convert.ToBase64String(Imgbytes);
                Imgbytes = System.Text.ASCIIEncoding.Default.GetBytes(s);
                try
                {
                    stream.Write(Imgbytes, 0, Imgbytes.Length);

                    string trailer = " \"/>";
                    b = System.Text.ASCIIEncoding.Default.GetBytes(trailer);
                    stream.Write(b, 0, b.Length);


                    // Shutdown and end connection
                    client.Close();
                }
                catch (Exception ex)
                {
                }
            }

            if (!StopThread)
            {
                server.BeginAcceptTcpClient(ConnectionAccepted, server);
            }
        }
Example #38
0
    void Start(int port)
    {
        try {
            System.Net.IPEndPoint ipLocalEndPoint = new System.Net.IPEndPoint(_ipAddress, port);

            //_newClientBackWorker.WorkerReportsProgress = true;
            //_newClientBackWorker.WorkerSupportsCancellation = true;
            //_newClientBackWorker.RunWorkerAsync();

            _serverSocket = new TcpListener(ipLocalEndPoint);

            _serverSocket.Start();
            _serverSocket.BeginAcceptTcpClient(Accept, _serverSocket);
        } catch (Exception ex) {
            Console.WriteLine(ex.ToString());
            error_text = ex.ToString();
        }
    }
        private void AcceptCallback(IAsyncResult iar)
        {
            try
            {
                System.Net.Sockets.TcpListener listener = (System.Net.Sockets.TcpListener)iar.AsyncState;
                _connector  = listener.EndAcceptTcpClient(iar);
                _dataStream = _connector.GetStream();

                StateObject receveieData = new StateObject();
                receveieData.client = _connector;

                _dataStream.BeginRead(receveieData.buffer, 0, receveieData.buffer.Length, AcceptData, receveieData);
                _listener.BeginAcceptTcpClient(AcceptCallback, _listener);
            }
            catch (Exception ex)
            {
                SFLib.Logger.Exception(ex.Message);
            }
        }
Example #40
0
        /// <summary>
        /// Comprueba si hay nuevos clientes para conectar
        /// </summary>
        private void ComprobarClienteConectado(IAsyncResult ar)
        {
            if (clientes == null)
            {
                clientes = new List <ClienteTCP>();
            }

            if (AceptarNuevasConexiones)
            {
                try
                {
                    ClienteTCP nuevoCliente = new ClienteTCP(listener.EndAcceptTcpClient(ar), "Servidor");
                    clientes.Add(nuevoCliente);

                    nuevoCliente.DatosRecibidos += new DelegadoComandoRecibido(DatosClienteRecibidos);
                    //Esperar más clientes
                    listener.BeginAcceptTcpClient(new AsyncCallback(ComprobarClienteConectado), null);

                    //Invocar el evento
                    InvocarEvento(ClienteConectado, ControlInvoke, nuevoCliente, null);
                }
                catch { }
            }
        }
Example #41
0
        public ServerListener(ProgramSettings settings)
        {
            if (null == settings)
            {
                throw new ArgumentNullException("settings");
            }
            if (0 == settings.ServerPort)
            {
                throw new ApplicationException();
            }

            m_Settings = settings;

            m_tcpListener = new SOCK.TcpListener(
                new NET.IPEndPoint(NET.IPAddress.Any, settings.ServerPort)
                );
            m_tcpListener.Start();
            m_tcpListener.BeginAcceptTcpClient(OnConnect, null);

            m_Settings.WriteMessageToLog(
                LogMessageType.Information,
                string.Format(CultureInfo.CurrentUICulture, "SipTunnel server started and is listening on port {0}.", m_Settings.ServerPort)
                );
        }
Example #42
0
 public void BeginAcceptTcpClient(System.Windows.Forms.MethodInvoker streamEstablishedHandler)
 {
     IAsyncResult ar = tcpListener.BeginAcceptTcpClient(new AsyncCallback(this.AcceptTcpClientCallback), streamEstablishedHandler);
     //TcpClient tcpClient = tcpListener.AcceptTcpClient();//blocking call
 }