EndAccept() public method

public EndAccept ( IAsyncResult asyncResult ) : Socket
asyncResult IAsyncResult
return Socket
Example #1
0
        void OnNewClient(IAsyncResult _asyncResult)
        {
            System.Net.Sockets.Socket ClientSocket = ListenSocket.EndAccept(_asyncResult);
            ListenSocket.BeginAccept(OnNewClient, null);

            SetKeepAlive(ClientSocket, 1000 * 60, 1000);

            var NewClient = new TelnetClient {
                Socket = ClientSocket
            };

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

                ClientSocket.BeginReceive(NewClient.Storage, 0, 1024, System.Net.Sockets.SocketFlags.Partial, OnData, NewClient);
                Console.WriteLine("New telnet client: " + ClientSocket.RemoteEndPoint.ToString());
            }
        }
Example #2
0
 private void _Accept(IAsyncResult iar)
 {
     if (_Socket == null)
     {
         return;
     }
     System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)iar.AsyncState;
     try
     {
         Clients.Add(client.EndAccept(iar));
         StateObject state = new StateObject();
         state.workSocket = Clients[Clients.Count - 1];
         ConnectionReceived?.Invoke(Clients[Clients.Count - 1]);
         Clients[Clients.Count - 1].BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(_OnReceive), state);
         _Socket.BeginAccept(new AsyncCallback(_Accept), client);
     }
     catch (Exception ex)
     {
         if (ex is ObjectDisposedException)
         {
             return;
         }
         //C_Error.WriteErrorLog("DamperData", ex);
         throw;
     }
 }
Example #3
0
        public static void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                System.Net.Sockets.Socket workerSocket = m_mainSocket.EndAccept(asyn);
                Interlocked.Increment(ref m_clientCount);
                m_workerSocketList.Add(workerSocket);

                WaitForData(workerSocket, m_clientCount);
                string msg = "Client " + m_clientCount + " Connected" + "\n";
                if (OutputClientChanged != null)
                {
                    OutputClientChanged(null, msg);
                }
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
            }
        }
Example #4
0
 private void _Accept(IAsyncResult Ar)
 {
     try
     {
         System.Net.Sockets.Socket socket = _Socket.EndAccept(Ar);
         _AcceptEvent(new Peer(socket));
         _Socket.BeginAccept(_Accept, state: null);
     }
     catch (SocketException se)
     {
         Singleton <Log> .Instance.WriteInfo(se.ToString());
     }
     catch (ObjectDisposedException ode)
     {
         Singleton <Log> .Instance.WriteInfo(ode.ToString());
     }
     catch (InvalidOperationException ioe)
     {
         Singleton <Log> .Instance.WriteInfo(ioe.ToString());
     }
     catch (Exception e)
     {
         Singleton <Log> .Instance.WriteInfo(e.ToString());
     }
 }
Example #5
0
        /// <summary>
        /// Create 2 sockets connected to each other, for communication between threads.
        /// </summary>
        public static Socket[] SocketPair()
        {
            Socket Listener;
            Socket[] Pair = new Socket[2];

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

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

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

            Listener.Close();

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

            return Pair;
        }
Example #6
0
        //BeginAcceptのコールバック
        private static void AcceptCallback(System.IAsyncResult ar)
        {
            allDone.Set();
            //サーバーSocketの取得
            System.Net.Sockets.Socket server = (System.Net.Sockets.Socket)ar.AsyncState;

            //接続要求を受け入れる
            System.Net.Sockets.Socket client = null;
            try
            {
                //クライアントSocketの取得
                client = server.EndAccept(ar);
            }
            catch
            {
                System.Console.WriteLine("閉じました。");
                return;
            }

            //クライアントが接続した時の処理をここに書く
            //ここでは文字列を送信して、すぐに閉じている
            client.Send(System.Text.Encoding.UTF8.GetBytes("こんにちは。"));

            Thread.Sleep(1000);
            client.Shutdown(System.Net.Sockets.SocketShutdown.Both);
            client.Close();
        }
Example #7
0
        private void Accept(IAsyncResult Ar)
        {
            try
            {
                var socket = m_Socket.EndAccept(Ar);
                lock (Acctpe)
                {
                    Acctpe(new Peer(socket));
                }

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


            catch (SocketException se)
            {
                Singleton <Log> .Instance.WriteInfo(se.ToString());
            }
            catch (ObjectDisposedException ode)
            {
                Singleton <Log> .Instance.WriteInfo(ode.ToString());
            }
            catch (InvalidOperationException ioe)
            {
                Singleton <Log> .Instance.WriteInfo(ioe.ToString());
            }
            catch (Exception e)
            {
                Singleton <Log> .Instance.WriteInfo(e.ToString());
            }
        }
Example #8
0
        public static void Server()
        {
            //创建一个新的Socket,这里我们使用最常用的基于TCP的Stream Socket(流式套接字)
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //将该socket绑定到主机上面的某个端口

            socket.Bind(new IPEndPoint(IPAddress.Any, 8001));

            //启动监听,并且设置一个最大的队列长度

            socket.Listen(4);

            //开始接受客户端连接请求

            socket.BeginAccept(new AsyncCallback((ar) =>
            {
                //这就是客户端的Socket实例,我们后续可以将其保存起来
                var client = socket.EndAccept(ar);

                //给客户端发送一个欢迎消息
                //client.Send(Encoding.Unicode.GetBytes("Hi there, I accept you request at " + DateTime.Now.ToString()));

                //实现每隔两秒钟给服务器发一个消息
                //这里我们使用了一个定时器
                /*var timer = new System.Timers.Timer();
                timer.Interval = 2000D;
                timer.Enabled = true;
                timer.Elapsed += (o, a) =>
                {
                    //检测客户端Socket的状态
                    if (client.Connected)
                    {
                        try
                        {
                            client.Send(Encoding.Unicode.GetBytes("Message from server at " + DateTime.Now.ToString()));
                        }
                        catch (SocketException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                    else
                    {
                        timer.Stop();
                        timer.Enabled = false;
                        Console.WriteLine("Client is disconnected, the timer is stop.");
                    }
                };
                timer.Start();*/

                //接收客户端的消息(这个和在客户端实现的方式是一样的)
                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);

            }), null);
        }
Example #9
0
 private void OnConnectRequest(IAsyncResult ar)
 {
     try
     {
         System.Net.Sockets.Socket listener = (System.Net.Sockets.Socket)ar.AsyncState;
         NewConnection(listener.EndAccept(ar));
         listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
     }
     catch { }
 }
 // Подключение клиентов
 private static void EndAccept(IAsyncResult ar)
 {
     try
     {
         Listener_Socket = (Socket)ar.AsyncState;
         AddClient(Listener_Socket.EndAccept(ar));
         Listener_Socket.BeginAccept(new AsyncCallback(EndAccept), Listener_Socket);
     }
     catch (Exception) { }
 }
Example #11
0
		//[Test]
		public void TestConnect28()
		{
			for (int i = 0; i < 1000; ++i)
			{
				const AddressFamily family = AddressFamily.InterNetwork;
				const SocketType socket = SocketType.Stream;
				const ProtocolType protocol = ProtocolType.Tcp;
				using (var client = new Socket(family, socket, protocol))
				using (var server = new Socket(family, socket, protocol))
				{
					client.ReceiveTimeout = 10000;

					server.ExclusiveAddressUse = true;
					server.Bind(new IPEndPoint(IPAddress.Loopback, 60310));

					bool isConnected = false;
					server.Listen(1);
					server.BeginAccept(ar =>
						{
							Console.WriteLine("BeginAccept handler");
							var serverCon = server.EndAccept(ar);
							Console.WriteLine("EndAccept called");

							isConnected = true;
							serverCon.Send(new byte[256]);
						}, null);

					try
					{
						client.Connect(server.LocalEndPoint);
						Console.WriteLine("socket.Connected: {0} to {1}", client.Connected, client.RemoteEndPoint);
					}
					catch (Exception e)
					{
						throw new Exception(string.Format("Connect failed: {0}", e.Message), e);
					}

					client.Send(new byte[256]);

					try
					{
						int length = client.Receive(new byte[256]);
						Assert.AreEqual(length, 256);
					}
					catch (Exception e)
					{
						throw new Exception(string.Format("Receive #{0} failed (Connected: {1}): {2}",
						                                  i,
						                                  isConnected,
						                                  e.Message),
						                    e);
					}
				}
			}
		}
Example #12
0
        private void Accept(IAsyncResult res)
        {
            var clientSocket = Server.EndAccept(res);

            clientSocket.ReceiveBufferSize = ClientBufferSize;
            var client = new NetworkClient(this, clientSocket, ClientBufferSize);

            OnConnect?.Invoke(client);
            client.BeginReceive();
            BeginAccept();
        }
Example #13
0
        void AcceptCallback(IAsyncResult ar)
        {
            try {
                var sock = socket.EndAccept(ar);

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

                Enqueue(delegate {
                    acceptedCallback(new Socket(Context, sock));
                });
            } catch {
            }
            socket.BeginAccept(AcceptCallback, null);
        }
Example #15
0
        private void ListenCallback(IAsyncResult ar)
        {
            try {
                System.Net.Sockets.Socket listener = ar.AsyncState as System.Net.Sockets.Socket;
                if (listener == null)
                {
                    //throw (new Exception("Listener Socket no longer exists"));
                    Exceptions.ErrorLogger.WriteToErrorLog(new Exception("Listener socket no longer exists"), "Listener socket no longer exists");
                }

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

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

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

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

                    DataAsyncState state = new DataAsyncState(bufferSize, client, index);
                    if (client.Connected)
                    {
                        client.BeginReceive(state.Data, 0, bufferSize, SocketFlags.None,
                                            new AsyncCallback(RecieveCallback), state);
                    }
                }
                listener.BeginAccept(new AsyncCallback(ListenCallback), listener);
            } catch (ObjectDisposedException ex) {
                Exceptions.ErrorLogger.WriteToErrorLog(ex, "Disposed exception, server listener.");
                serverSocket.BeginAccept(new AsyncCallback(ListenCallback), serverSocket);
                return;
            } catch (SocketException socketex) {
                Exceptions.ErrorLogger.WriteToErrorLog(socketex, "Socket exception, server listener.");
                RaiseError(socketex.Message, "", (SocketError)socketex.ErrorCode);
                serverSocket.BeginAccept(new AsyncCallback(ListenCallback), serverSocket);
            } catch (Exception ex) {
                Exceptions.ErrorLogger.WriteToErrorLog(ex, "Normal exception, server listener.");
                serverSocket.BeginAccept(new AsyncCallback(ListenCallback), serverSocket);
            }
        }
 private void ConnectionRequested(System.IAsyncResult oResult)
 {
     oServer = (System.Net.Sockets.Socket)oResult.AsyncState;
     oClient = oServer.EndAccept(oResult);
     Console.WriteLine("Received connection request from " + oClient.RemoteEndPoint.ToString());
     bWaitingForConnection = false;
     bConnected            = true;
     if (TCPConnectChangedEvent != null)
     {
         TCPConnectChangedEvent(bConnected);
     }
     f_WaitForData(oClient);
 }
Example #17
0
        internal void OnAcceptReceived(IAsyncResult ar)
        {
            System.Net.Sockets.Socket sman = (System.Net.Sockets.Socket)ar.AsyncState;

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

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

                if (newsocket == null)
                {
                    return;
                }

                System.Diagnostics.Debug.WriteLine("Accepted new socket {0}", newsocket.Handle);
                if (OnNewConnection != null)
                {
                    OnNewConnection(newsocket);
                }
            }
        }
Example #18
0
        private void AcceptConnection(IAsyncResult ar)
        {
            try
            {
                Socket ClientSocket = RawSocket.EndAccept(ar);
                RawSocket.BeginAccept(new AsyncCallback(AcceptConnection), RawSocket);

                SocketConnection socketConnection = new SocketConnection(this, ClientSocket);
                SocketConnections.Add(socketConnection);
                SocketConnectionConnected_Event(this, socketConnection);

                Console.Title = string.Format("{0} Active Connection - {1} Packets Received - {2} Packets Sent", SocketConnections.Count, PacketsReceived, PacketsSent);
            }
            catch { }
        }
        public SSPClient ProcessClient(SSPServer Server, Socket TcpServer, IAsyncResult result)
        {
            try
            {
                Socket AcceptSocket = TcpServer.EndAccept(result); //<- can throw a error
                SSPClient client = Server.GetNewClient();
                client.Handle = AcceptSocket;

                if (AcceptSocket.AddressFamily == AddressFamily.InterNetworkV6)
                    client.RemoteIp = ((IPEndPoint)AcceptSocket.RemoteEndPoint).Address.ToString();
                else
                    client.RemoteIp = AcceptSocket.RemoteEndPoint.ToString().Split(':')[0];

                client.Server = Server;
                client.Connection = new Network.Connection(client);
                client.ClientId = Server.randomDecimal.NextDecimal();

                client.serverHS = new ServerMaze(Server.serverProperties.Handshake_Maze_Size, Server.serverProperties.Handshake_MazeCount, Server.serverProperties.Handshake_StepSize);
                client.serverHS.onFindKeyInDatabase += Server.serverHS_onFindKeyInDatabase;

                SysLogger.Log("Accepted peer " + client.RemoteIp, SysLogType.Debug);

                lock (Server.Clients)
                {
                    while (Server.Clients.ContainsKey(client.ClientId))
                        client.ClientId = Server.randomDecimal.NextDecimal();
                    Server.Clients.Add(client.ClientId, client);
                }

                try
                {
                    client.onBeforeConnect();
                }
                catch (Exception ex)
                {
                    SysLogger.Log(ex.Message, SysLogType.Error);
                    client.onException(ex, ErrorType.UserLand);
                }

                client.Connection.StartReceiver();
                return client;
            }
            catch (Exception ex)
            {
                SysLogger.Log(ex.Message, SysLogType.Error);
                return null;
            }
        }
Example #20
0
 /// <summary>
 /// Asyncs the connect.
 /// </summary>
 /// <param name="socket">The socket.</param>
 /// <param name="accept">The accept.</param>
 /// <param name="timeout">The timeout.</param>
 private static Socket AsyncAccept(Socket socket, Func<Socket, AsyncCallback, object, IAsyncResult> accept, TimeSpan timeout)
 {
     var asyncResult = accept(socket, null, null);
     if (asyncResult.AsyncWaitHandle.WaitOne(timeout))
     {
         try
         {
             return socket.EndAccept(asyncResult);
         }
         catch (SocketException)
         { }
         catch (ObjectDisposedException)
         { }
     }
     return null;
 }
Example #21
0
        private void OnNewConnection(IAsyncResult asyncResult)
        {
            System.Net.Sockets.Socket client;
            try
            {
                client = _listenerSocket.EndAccept(asyncResult);
            } catch (ObjectDisposedException) {
                // ignore, happens during shutdown
                return;
            }

            client.NoDelay = true;

            _listenerSocket.BeginAccept(OnNewConnection, this);

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

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

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

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        private void AcceptCallback(IAsyncResult ar)
        {
            System.Net.Sockets.Socket socket;

            try
            {
                socket = _serverSocket.EndAccept(ar);
                _clientSockets.Add(socket);
                socket.BeginReceive(_buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket);
                Console.WriteLine("Client connected: " + socket.RemoteEndPoint);
                _serverSocket.BeginAccept(AcceptCallback, null);
            }
            catch (Exception e)
            {
                // Log.Error
            }
        }
Example #23
0
        private void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            AllDone.Set();

            // Get the socket that handles the client request.
            System.Net.Sockets.Socket listener = (System.Net.Sockets.Socket)ar.AsyncState;
            System.Net.Sockets.Socket handler  = listener.EndAccept(ar);

            // Create the state object.
            var state = new StateObject {
                workSocket = handler
            };

            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                 new AsyncCallback(ReadCallback), state);
        }
Example #24
0
        private void AcceptCallback(IAsyncResult result)
        {
            ClientConnection conn = null;

            try
            {
                System.Net.Sockets.Socket s = (System.Net.Sockets.Socket)result.AsyncState;
                conn        = new ClientConnection();
                conn.socket = s.EndAccept(result);
                conn.buffer = new byte[BUFFER_SIZE];
                lock (mConnectionList)
                {
                    mConnectionList.Add(conn);
                }
                //Queue recieving of data from the connection
                conn.socket.BeginReceive(conn.buffer, 0, conn.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), conn);
                //Queue the accept of the next incomming connection
                mServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), mServerSocket);
                Program.Log.Info("Connection {0}:{1} has connected.", (conn.socket.RemoteEndPoint as IPEndPoint).Address, (conn.socket.RemoteEndPoint as IPEndPoint).Port);
            }
            catch (SocketException)
            {
                if (conn.socket != null)
                {
                    conn.socket.Close();
                    lock (mConnectionList)
                    {
                        mConnectionList.Remove(conn);
                    }
                }
                mServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), mServerSocket);
            }
            catch (Exception)
            {
                if (conn.socket != null)
                {
                    conn.socket.Close();
                    lock (mConnectionList)
                    {
                        mConnectionList.Remove(conn);
                    }
                }
                mServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), mServerSocket);
            }
        }
Example #25
0
 //服务端重载Access函数
 public override void Access(string IP, int ServerPort, int Port, System.Action AccessAciton)
 {
     Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     //设置SOCKET允许多个SOCKET访问同一个本地IP地址和端口号
     serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
     //本机预使用的IP和端口
     IPEndPoint serverIP = new IPEndPoint(IPAddress.Any, ServerPort);
     //绑定服务端设置的IP
     serverSocket.Bind(serverIP);
     //设置监听个数
     serverSocket.Listen(1);
     //异步接收连接请求
     serverSocket.BeginAccept(ar =>
         {
             base.communicateSocket = serverSocket.EndAccept(ar);
             AccessAciton();
         }, null);
 }
Example #26
0
        public void OnClientConnect(IAsyncResult asyn)
        {
            try {
                System.Net.Sockets.Socket workerSocket = mainSocket.EndAccept(asyn);
                Interlocked.Increment(ref clientCount);
                workerSocketList.Add(workerSocket);

                // SendMsgToClient(msg, clientCount - 1);

                UpdateClientList();
                WaitForData(workerSocket, clientCount);
                mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            } catch (ObjectDisposedException) {
                Console.WriteLine("OnClientConnection: Socket has been closed\n");
            } catch (SocketException se) {
                Console.WriteLine(se.Message);
            }
        }
Example #27
0
        private void AcceptCallback(IAsyncResult ar)
        {
            // Get the listener that handles the client request.
            System.Net.Sockets.Socket listener = (System.Net.Sockets.Socket)ar.AsyncState;

            if (listener != null)
            {
                System.Net.Sockets.Socket handler = listener.EndAccept(ar);

                // Signal main thread to continue
                allDone.Set();

                // Create state
                StateObject state = new StateObject();
                state.workSocket = handler;
                handler.BeginReceive(state.buffer, 0, _bufferSize, 0, new AsyncCallback(ReadCallback), state);
            }
        }
        public void ConnectTest()
        {
            ManualResetEvent trigger = new ManualResetEvent( false );
            bool isConnected = false;

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

            IPHostEntry dnsEntry = Dns.GetHostEntry( "localhost" );

            // If this fails, consider changing the index. This could fail depending on the
            // physical configuration of the host system.
            IPEndPoint endPoint =
                new IPEndPoint( dnsEntry.AddressList[1], 8089 );

            socket.Bind( endPoint );

            socket.Listen( 30 );

            socket.BeginAccept( s =>
                                {
                                    socket.EndAccept( s );
                                    isConnected = true;
                                    trigger.Set();
                                },
                                null );

            Mock<ICoreSettings> settings = new Mock<ICoreSettings>();

            NetworkFacadeFactory factory = new NetworkFacadeFactory(settings.Object);
            factory.BeginConnect( "localhost",
                                  8089,
                                  ( b, s ) =>
                                  {
                                      Assert.That( b, Is.True );
                                      Assert.That( s, Is.Not.Null );
                                  } );

            Assert.That( trigger.WaitOne( 2000 ), Is.True );
            Assert.That( isConnected, Is.True );
        }
Example #29
0
 public void WaitForConnections()
 {
     Socket serverSocket = null;
     try
     {
         serverSocket = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         serverSocket.Bind(new IPEndPoint(IPAddress.Any, _socketPort));
         serverSocket.Listen(5);
         while (true)
         {
             try
             {
                 IAsyncResult res = serverSocket.BeginAccept(null, null);
                 Socket client = serverSocket.EndAccept(res);
                 var ct = new ClienteTcp(client, _endLine);
                 var t = new Thread(ct.TreatClient);
                 t.Name = "Socket treatClient";
                 t.Start();
             }
             catch (ThreadAbortException)
             {
                 serverSocket.Close();
                 break;
             }
             catch (Exception ex)
             {
                 EventLog.WriteEntry("low-level-sendkeys", string.Format("low-level-sendkeys error loop:\n{0}", ex), EventLogEntryType.Error);
                 Thread.Sleep(5000);
             }
         }
     }
     catch (ThreadAbortException)
     {
         if (serverSocket != null) serverSocket.Close();
     }
     catch (Exception ex)
     {
         EventLog.WriteEntry("low-level-sendkeys", string.Format("low-level-sendkeys error:\n{0}", ex), EventLogEntryType.Error);
         throw;
     }
 }
Example #30
0
        private void acceptCallback(IAsyncResult result)
        {
            xConnection conn = null;             // new xConnection();

            try {
                //Finish accepting the connection
                System.Net.Sockets.Socket s = (System.Net.Sockets.Socket)result.AsyncState;
                conn        = new xConnection();
                conn.socket = s.EndAccept(result);
                conn.buffer = new byte[_bufferSize];
                conn.server = this;
                lock (_sockets) {
                    _sockets.Add(conn);
                }
                //Queue recieving of data from the connection
                conn.socket.BeginReceive(conn.buffer, 0, conn.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), conn);
                //Queue the accept of the next incomming connection
                _serverSocket.BeginAccept(new AsyncCallback(acceptCallback), _serverSocket);
            } catch (SocketException) {
                if (conn.socket != null)
                {
                    conn.socket.Close();
                    lock (_sockets) {
                        _sockets.Remove(conn);
                    }
                }
                //Queue the next accept, think this should be here, stop attacks based on killing the waiting listeners
                _serverSocket.BeginAccept(new AsyncCallback(acceptCallback), _serverSocket);
            } catch (Exception) {
                if (conn.socket != null)
                {
                    conn.socket.Close();
                    lock (_sockets) {
                        _sockets.Remove(conn);
                    }
                }
                //Queue the next accept, think this should be here, stop attacks based on killing the waiting listeners
                _serverSocket.BeginAccept(new AsyncCallback(acceptCallback), _serverSocket);
            }
        }
Example #31
0
        private void _instance_endAccept(IAsyncResult res)
        {
            Core.EventLoop.Instance.Push(() =>
            {
                var rawSocket = nativeSocket.EndAccept(res);

                var socket = new Socket(rawSocket);

                if (OnConnection != null)
                {
                    Core.EventLoop.Instance.Push(() =>
                    {
                        OnConnection(socket);
                    });
                }

                Core.EventLoop.Instance.Push(() =>
                {
                    _acceptConnection();
                });
            });
        }
Example #32
0
File: test.cs Project: mono/gert
		public static void Main (string [] args)
		{
			IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10000);
			Socket accept = new Socket (AddressFamily.InterNetwork,
				SocketType.Stream, ProtocolType.Tcp);
			Socket client = new Socket (AddressFamily.InterNetwork,
				SocketType.Stream, ProtocolType.Tcp);
			Socket listener = new Socket (AddressFamily.InterNetwork,
				SocketType.Stream, ProtocolType.Tcp);

			listener.Bind (ep);
			listener.Listen (8);
			IAsyncResult listenResult = listener.BeginAccept (accept,
				0, null, null);

			client.Connect (ep);
			Assert.IsFalse (accept.Connected, "#1");

			Socket connected = listener.EndAccept (listenResult);
			Assert.IsTrue (accept.Connected, "#2");
			Assert.AreSame (connected, accept, "#3");
		}
        /// <summary>
        /// 异步接收连接
        /// </summary>
        /// <param name="ar"></param>
        private void AsyncAcceptConnectCallback(IAsyncResult ar)
        {
            SocketState state = new SocketState();

            try
            {
                System.Net.Sockets.Socket listener = (System.Net.Sockets.Socket)ar.AsyncState;
                System.Net.Sockets.Socket handler  = listener.EndAccept(ar);
                //int keepAlive = -1744830460; // SIO_KEEPALIVE_VALS
                //byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 }; //True, 20 秒, 2 秒
                //handler.IOControl(keepAlive, inValue, null);


                //handler.SendTimeout = SendTimeOutMS;
                //handler.ReceiveTimeout = ReceiveTimeOutMS;

                state            = new SocketState();
                state.workSocket = handler;
                base.SetHeartBeat(state);

                connectDone.Set();

                state.IsReceiveThreadAlive = true;
                SetConnection(true, state);
                handler.BeginReceive(state.buffer, 0, 2, 0, new AsyncCallback(AsyncReceivedCallback), state);
            }
            catch (System.Net.Sockets.SocketException SktEx)
            {
                WriteLog(SktEx, SktEx.ErrorCode.ToString());
                SetConnection(false, state);
            }
            catch (Exception Ex)
            {
                WriteLog(Ex, null);
                SetConnection(false, state);
            }
        }
Example #34
0
        private void OnNewConnection(IAsyncResult asyncResult)
        {
            System.Net.Sockets.Socket client = _listenerSocket.EndAccept(asyncResult);
            client.NoDelay = true;

            _listenerSocket.BeginAccept(OnNewConnection, this);

            switch (_sessionType)
            {
            case EnumSessionType.Telnet:
            {
                _logger.Info($"Accepting incoming Telnet connection from {client.RemoteEndPoint}...");
                var telnetSession = new TelnetSession(client);
                break;
            }

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

                _logger.Info($"Accepting incoming Rlogin connection from {client.RemoteEndPoint}...");
                var rloginSession = new RloginSession(client, _moduleIdentifier);
                break;
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public HttpClientContextTest()
        {
            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listenSocket.Bind(new IPEndPoint(IPAddress.Any, 14862));
            _listenSocket.Listen(0);
            IAsyncResult res = _listenSocket.BeginAccept(null, null);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _client.Connect("localhost", 14862);
            _remoteSocket = _listenSocket.EndAccept(res);

            _disconnectEvent.Reset();
            _event.Reset();
            _counter = 0;

            var requestParserFactory = new RequestParserFactory();
            _factory = new HttpContextFactory(NullLogWriter.Instance, 8192, requestParserFactory);
            _factory.RequestReceived += OnRequest;
            _context = _factory.CreateContext(_client);
            _context.Disconnected += OnDisconnect;
            //_context = new HttpClientContextImp(false, new IPEndPoint(IPAddress.Loopback, 21111), OnRequest, OnDisconnect, _client.GetStream(), ConsoleLogWriter.Instance);

            _request = null;
            _disconnected = false;
        }
Example #36
0
        /// <summary>
        /// Elfogadja a bejövő kliens kapcsolatát
        /// Felkészül az adatfogadásra
        /// </summary>
        /// <param name="ar">Aszinkron paraméter</param>
        private void acceptConnection(IAsyncResult ar)
        {
            Socket handler = null, listener = null;

            try {
                listener = (Socket)ar.AsyncState;
                handler = listener.EndAccept(ar);
                clients.Add(handler);

                byte[] headerbuffer = new byte[4];
                object[] obj = new object[2];
                obj[0] = headerbuffer;
                obj[1] = handler;
                handler.BeginReceive(headerbuffer, 0, headerbuffer.Length, SocketFlags.None, new AsyncCallback(receiveHeader), obj);
                listener.BeginAccept(new AsyncCallback(acceptConnection), listener);
            } catch (Exception) {
                // client connection error
            }
        }
        public void ServerSocketDisconnectTest() {
            _log.Debug("creating socket");
            var ipEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), _port);
            var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
            listenSocket.Bind(ipEndpoint);
            listenSocket.Listen((int)SocketOptionName.MaxConnections);
            Socket requestSocket = null;

            // accept requests
            AsyncCallback onAccept = result => {
                requestSocket = listenSocket.EndAccept(result);

                // read from socket
                var receiveBuffer = new byte[5];
                if(requestSocket.Connected) {
                    requestSocket.Receive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None);
                    requestSocket.Send(Response.Create("OK").GetBytes());
                }
            };
            listenSocket.BeginAccept(onAccept, listenSocket);
            _log.Debug("created socket");

            // create client
            using (var client = new ClacksClient("127.0.0.1", _port)) {
                Assert.IsFalse(client.Disposed);
                var response = client.Exec(new Client.Request("HELLO"));
                _log.InfoFormat("Received response with status: {0}", response.Status);
                Assert.AreEqual("OK", response.Status, "Excpected OK status");

                // disconnect server socket
                requestSocket.Shutdown(SocketShutdown.Both);
                requestSocket.Disconnect(reuseSocket: true);

                // create new socket and try another request
                listenSocket.BeginAccept(onAccept, listenSocket);
                response = client.Exec(new Client.Request("HELLO"));
                _log.InfoFormat("Received response with status: {0}", response.Status);
                Assert.AreEqual("OK", response.Status, "Excpected OK status");
            }
        }
Example #38
0
 //服务端重载Access函数
 public override void Access(string IP, string Port, string PortSelf, System.Action AccessAction)
 {
     Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     //本机预使用的IP和端口
     IPEndPoint serverIP = new IPEndPoint(IPAddress.Any, int.Parse(PortSelf));
     //绑定服务端设置的IP
     serverSocket.Bind(serverIP);
     //设置监听个数
     serverSocket.Listen(5);
     //异步接收连接请求
     serverSocket.BeginAccept(ar =>
         {
             Socket temp =serverSocket.EndAccept(ar);
             if (communicateSockets.Count == 0)
             {
                 communicateSocket = temp;
             }
                 communicateSockets.Add(temp);
             AccessAction();
         }, null);
 }
Example #39
0
        private void ConnectionAccept(SocketPurpose Purpose, Socket ListenSocket, IAsyncResult ar)
        {
            bool SetDeviceInUse = false;
            Socket NetworkSocket = null;

            try
            {
                NetworkSocket = ListenSocket.EndAccept(ar);
                IPEndPoint RemoteEP = (IPEndPoint)NetworkSocket.RemoteEndPoint;
                System.Console.WriteLine("{0} connected from {1}:{2}", SocketName(Purpose),
                    RemoteEP.Address, RemoteEP.Port);

                lock (this)
                {
                    if (DeviceInUse) //Something already using the device
                    {
                        System.Console.WriteLine("Device in use, closing {0} connection", SocketName(Purpose));

                        NetworkSocket.Close();
                        NetworkSocket = null;

                        CloseListenSocket(Purpose);

                        return;
                    }
                    else //Otherwise set the flag as we're using the device
                    {
                        DeviceInUse = true;
                        SetDeviceInUse = true;

                        CurrentNetworkSocket = NetworkSocket;

                        CloseListenSocket(Purpose);
                    }
                }

                NetworkSocket.BeginReceive(networkBuf, 0, 1024, SocketFlags.None,
                    delegate(IAsyncResult AsR){NetworkReceive(Purpose, NetworkSocket, AsR);},
                    null);
            }
            catch (SocketException e)
            {
                Console.WriteLine("Error accepting connection from {0} (errcode: {1})", SocketName(Purpose), e.SocketErrorCode);
                CloseListenSocket(Purpose);

                if (NetworkSocket != null)
                    NetworkSocket.Close();

                if (SetDeviceInUse)
                    DeviceInUse = false;

                StartListen();
            }
            catch (ObjectDisposedException)
            {
                Console.WriteLine("Error accepting connection from {0}, the socket was closed", SocketName(Purpose));
                CloseListenSocket(Purpose);

                if (NetworkSocket != null)
                    NetworkSocket.Close();

                if (SetDeviceInUse)
                    DeviceInUse = false;

                StartListen();
            }
        }
Example #40
0
 public ISocket EndAccept(IAsyncResult asyncResult)
 {
     return(new Socket(_socket.EndAccept(asyncResult)));
 }
Example #41
0
        public void Start(IPEndPoint pedListenEndpoint)
        {
            Ensure.NotNull(pedListenEndpoint, nameof(pedListenEndpoint));

            _pedListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _pedListenSocket.Bind(pedListenEndpoint);
            _pedListenSocket.Listen(10);

            AsyncCallback beginAccept = null;
            beginAccept = acceptResult =>
            {
                try
                {
                    Socket connectedPedSocket = _pedListenSocket.EndAccept(acceptResult);

                    byte[] lengthBuffer = new byte[2];
                    int readCount = 0;

                    AsyncCallback beginReceive = null;
                    beginReceive = receiveResult =>
                    {
                        try
                        {
                            readCount += connectedPedSocket.EndReceive(receiveResult);
                            if (readCount != 2)
                            {
                                connectedPedSocket.BeginReceive(lengthBuffer, readCount, lengthBuffer.Length, SocketFlags.None, beginReceive, null);
                                return;
                            }

                            int length = (lengthBuffer[0] << 8) + lengthBuffer[1];
                            if (length < 1 || length > 65280)
                                throw new Exception($"Invalid message length received [{length}]");

                            byte[] data = new byte[length];

                            readCount = 0;
                            while (readCount < data.Length)
                            {
                                connectedPedSocket.ReceiveTimeout = 2000;

                                int count = connectedPedSocket.Receive(data, readCount, data.Length - readCount, SocketFlags.None);
                                if (count == 0)
                                    throw new Exception("Socket closed on read operation");

                                readCount += count;
                            }

                            if (readCount != length)
                                throw new Exception("Cannot receive full message");

                            try
                            {
                                Process(connectedPedSocket, data);
                            }
                            catch (Exception ex)
                            {
                                Log.Error(ex);
                            }

                            connectedPedSocket.BeginReceive(lengthBuffer, readCount = 0, lengthBuffer.Length, SocketFlags.None, beginReceive, null);
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);

                            try
                            {
                                connectedPedSocket.Shutdown(SocketShutdown.Both);
                                connectedPedSocket.Close();
                            }
                            catch { }
                        }
                    };

                    connectedPedSocket.BeginReceive(lengthBuffer, 0, lengthBuffer.Length, SocketFlags.None, beginReceive, null);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
                finally
                {
                    _pedListenSocket.BeginAccept(beginAccept, null);
                }
            };

            _pedListenSocket.BeginAccept(beginAccept, null);
        }
        public IAsyncResult Listen()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.Bind(new IPEndPoint(IPAddress.Loopback, 5050));
            _socket.Listen(1);

            return _socket.BeginAccept(delegate(IAsyncResult asyncResult)
            {
                try
                {
                    var client = _socket.EndAccept(asyncResult);

                    using (var networkStream = new NetworkStream(client))
                    using (var streamReader = new StreamReader(networkStream))
                    {
                        Assert.That(streamReader.ReadToEnd(), Is.EqualTo(_expectedText));
                    }

                }
                catch (ObjectDisposedException)
                {
                    Error = true;
                }

            }, null);
        }
Example #43
0
			void Start ()
			{
				socket = new Socket (
					AddressFamily.InterNetwork, SocketType.Stream,
					ProtocolType.Tcp);
				socket.Bind (new IPEndPoint (IPAddress.Loopback, 0));
				socket.Listen (1);
				socket.BeginAccept ((result) => {
					var accepted = socket.EndAccept (result);
					HandleRequest (accepted);
				}, null);
			}
Example #44
0
        private void AcceptCallback(IAsyncResult value)
        {
            try
            {
                if (ListenerSocker == null)
                {
                    return;
                }

                System.Net.Sockets.Socket socket = ListenerSocker.EndAccept(value);

                if (UseBlockList)
                {
                    string ip = IP(socket);
                    if (BlockClient.ContainsKey(ip))
                    {
                        if (BlockClient[ip].IsBlock)
                        {
                            if (BlockClient[ip].Timer > DateTime.Now.Ticks)
                            {
                                Log.Log.GetLog().Info(this, "AcceptCallback  Disconnect ip : " + ip);
                                socket.Disconnect(true);
                            }
                            else
                            {
                                BlockClient[ip] = new ClienteSocketBlock();
                            }
                        }
                    }
                }

                if (socket.Connected)
                {
                    getClientType(socket);
                }
            }
            catch (Exception e)
            {
                Log.Log.GetLog().Error(this, "AcceptCallback", e);
            }
            finally
            {
                try
                {
                    if (ListenerSocker != null)
                    {
                        ListenerSocker.BeginAccept(new AsyncCallback(AcceptCallback), null);
                    }
                }
                catch (Exception e)
                {
                    Log.Log.GetLog().Error(this, "AcceptCallback - ListenerSocker.BeginAccept", e);

                    try
                    {
                        close();
                    }
                    catch (Exception ex)
                    {
                        Log.Log.GetLog().Error(this, "AcceptCallback - ListenerSocker.BeginAccept - close", ex);
                    }

                    Thread.Sleep(2000);

                    try
                    {
                        startService();
                    }
                    catch (Exception ex)
                    {
                        Log.Log.GetLog().Error(this, "AcceptCallback - ListenerSocker.BeginAccept - startService", ex);
                    }
                }
            }

            OnDataChange();
        }
Example #45
0
 private void AcceptCallBack(IAsyncResult ar)
 {
     allDone.Set();
     listener = (Socket)ar.AsyncState;
     var handle = listener.EndAccept(ar);
     //handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
     var session = new Session(handle, bufferSize);
     Console.WriteLine("{0} connected at {1}", session.SessionID, session.Address);
     //Send(session, "hello client, welcome you!!!!!!!");
     UtilityHelper.RaiseEvent(OnNewClientConnected, session);
     session.BeginReceive(session.Buffer, 0, bufferSize, 0, new AsyncCallback(ReadCallback), session);
 }
Example #46
0
 Utils.Wrappers.Interfaces.ISocket Utils.Wrappers.Interfaces.ISocket.EndAccept(out byte[] buffer, System.IAsyncResult asyncResult)
 {
     return(new SocketWrapped(InternalSocket.EndAccept(out buffer, asyncResult)));
 }
Example #47
0
        public void OnConnectRequest(IAsyncResult ar)
        {
            try
            {
                Socket listener = (Socket)ar.AsyncState;

                if (client1_connected && client2_connected)
                {
                    Socket tmp_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    tmp_socket.EndAccept(ar);
                    tmp_socket.Close();
                    Listener.BeginAccept(new AsyncCallback(OnConnectRequest), Listener);

                    if (debug && !console.ConsoleClosing)
                        console.Invoke(new DebugCallbackFunction(console.DebugCallback),
                            "Client already connected!");
                }
                else if (client1_connected)
                    client2 = listener.EndAccept(ar);
                else
                    client1 = listener.EndAccept(ar);

                if (client1.Connected && !client1_connected)
                {
                    client1_connected = true;
                    ConnectionWatchdog.Enabled = true;
                    ConnectionWatchdog.Interval = WatchdogInterval;
                    ConnectionWatchdog.Start();

                    if (debug && !console.ConsoleClosing)
                        console.Invoke(new DebugCallbackFunction(console.DebugCallback),
                            "Client connected!");

                    client1.BeginReceive(receive_buffer1, 0, receive_buffer1.Length, SocketFlags.None, OnRecievedData, client1);
                    client1_hanle = client1.Handle;
                    Debug.Write("Client joined " + client1.RemoteEndPoint.ToString() + "\n");
                    listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);        // again
                }
                else if (client2.Connected && !client2_connected)
                {
                    client2_connected = true;
                    ConnectionWatchdog.Enabled = true;
                    ConnectionWatchdog.Interval = WatchdogInterval;
                    ConnectionWatchdog.Start();

                    if (debug && !console.ConsoleClosing)
                        console.Invoke(new DebugCallbackFunction(console.DebugCallback),
                            "Client connected!");

                    client2.BeginReceive(receive_buffer2, 0, receive_buffer2.Length, SocketFlags.None, OnRecievedData, client2);
                    client2_hanle = client2.Handle;
                    Debug.Write("Client joined " + client2.RemoteEndPoint.ToString() + "\n");
                    listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);        // again
                }
            }
            catch (Exception ex)
            {
                Debug.Write(ex.ToString());
            }
        }
Example #48
0
        //当有客户端连接时的处理
        public void OnConnectRequest(IAsyncResult ar)
        {
            //初始化一个SOCKET,用于其它客户端的连接
            server1 = (Socket)ar.AsyncState;
            Client = server1.EndAccept(ar);
            //将要发送给连接上来的客户端的提示字符串
            DateTimeOffset now = DateTimeOffset.Now;
            string strDateLine = "欢迎登录到服务器";
            Byte[] byteDateLine = System.Text.Encoding.UTF8.GetBytes(strDateLine);
            //将提示信息发送给客户端,并在服务端显示连接信息。
            remote = Client.RemoteEndPoint;
            showClientMsg(Client.RemoteEndPoint.ToString() + "连接成功。" + now.ToString("G")+"\r\n");
            Client.Send(byteDateLine, byteDateLine.Length, 0);
            userListOperate(Client.RemoteEndPoint.ToString());
            //把连接成功的客户端的SOCKET实例放入哈希表
            _sessionTable.Add(Client.RemoteEndPoint, null);

            //等待新的客户端连接
            server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1);

            while (true)
            {
                int recv = Client.Receive(byteDateLine);
                string stringdata = Encoding.UTF8.GetString(byteDateLine, 0, recv);
                string ip = Client.RemoteEndPoint.ToString();
                //获取客户端的IP和端口

                if (stringdata == "STOP")
                {
                    //当客户端终止连接时
                    showClientMsg(ip+"   "+now.ToString("G")+"  "+"已从服务器断开"+"\r\n");
                    _sessionTable.Remove(Client.RemoteEndPoint);
                    break;
                }
                //显示客户端发送过来的信息
                showClientMsg(ip + "  " + now.ToString("G") + "   " + stringdata + "\r\n");
            }
        }
Example #49
0
        void ProcessConnection(Socket listener, IAsyncResult ar)
        {
            Socket ns = listener.EndAccept (ar);
            ns.NoDelay = true;
            SslStream ssl = new SslStream (new NetworkStream (ns, true));

            ssl.BeginAuthenticateAsServer (cert, (IAsyncResult ar2) => {
                try {
                    ssl.EndAuthenticateAsServer (ar2);
                    Protocol p = new Protocol ();
                    p.OnMessage += (incoming) => {
                        var hdr = incoming.Header;
                        // TODO timeout handling
                        if (hdr ["type"].AsString(null) != "request") {
                            Logger.LogError ("received non-request");
                            incoming.Discard ();
                            return;
                        }
                        if (!hdr.ContainsKey ("request_id")) {
                            Logger.LogError ("Received request with no request_id");
                            incoming.Discard ();
                            return;
                        }
                        var id = hdr ["request_id"];
                        reqh (incoming, (reply) => {
                            reply.Header ["type"] = "reply";
                            reply.Header ["request_id"] = id;
                            p.SendMessage (reply);
                        });
                    };
                    p.OnClose += (error) => {
                        Logger.LogInfo ("scamp connection closed: {0}", error);
                    };
                    p.Start (ssl);
                } catch (Exception ex) {
                    Logger.LogError ("connection server authenticate: {0}", ex);
                }
            }, null);
        }
Example #50
0
    public IEnumerator<ITask> Listen(int port) {
      IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port);

      Socket ListenSocket = new Socket(endPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
      ListenSocket.Bind(endPoint);
      ListenSocket.Listen(1024);

      m_ListenerSocket = ListenSocket;

      m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_TRANSPORT,
        "SimpleFLM: Waiting for connections");

      while (m_ReloadConfig.State < ReloadConfig.RELOAD_State.Shutdown) {
        var iarPort = new Port<IAsyncResult>();
        Socket associatedSocket = null;

        ListenSocket.BeginAccept(iarPort.Post, null);
        
        yield return Arbiter.Receive(false, iarPort, iar => {
          try {
            associatedSocket = ListenSocket.EndAccept(iar);
          }
          catch (Exception ex) {
            m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, "Link.Listen: " + ex);
          }
        });        

        if (m_ReloadConfig.State < ReloadConfig.RELOAD_State.Shutdown) {
          m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET,
            String.Format("SimpleFLM: << {0} accepted client", associatedSocket.RemoteEndPoint));
          Arbiter.Activate(m_ReloadConfig.DispatcherQueue,
            new IterativeTask<Socket, NodeId>(associatedSocket, null, Receive));
        }
      }
      m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET, String.Format("SimpleFLM: << Exit from listen"));
    }
Example #51
0
        public void Start(IPEndPoint ficalPrinterEndpoint)
        {
            Ensure.NotNull(ficalPrinterEndpoint, nameof(ficalPrinterEndpoint));

            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listenSocket.Bind(ficalPrinterEndpoint);
            _listenSocket.Listen(2);

            AsyncCallback acceptCallback = null;
            acceptCallback = (acceptResult) =>
            {
                try
                {
                    Socket client = _listenSocket.EndAccept(acceptResult);

                    byte[] messageLength = new byte[2];
                    int receiveCount = 0;

                    AsyncCallback receiveCallback = null;
                    receiveCallback = (receiveResult) =>
                    {
                        try
                        {
                            receiveCount += client.EndReceive(receiveResult);
                            if (receiveCount != 2)
                            {
                                client.BeginReceive(messageLength, receiveCount, messageLength.Length, SocketFlags.None, receiveCallback, null);
                                return;
                            }

                            int length = (messageLength[0] << 8) + messageLength[1];
                            if (length < 1 || length > 65280)
                                throw new Exception($"Invalid message length received [{length}]");

                            byte[] data = new byte[length];

                            int readCount = 0;
                            while (readCount < data.Length)
                            {
                                client.ReceiveTimeout = 2000;

                                int count = client.Receive(data, readCount, data.Length - readCount, SocketFlags.None);
                                if (count == 0)
                                    throw new Exception("Socket closed on read operation");

                                readCount += count;
                            }

                            if (readCount != length)
                                throw new Exception("Cannot receive full message");

                            try
                            {
                                ProcessAsync(client, data);
                            }
                            catch(Exception ex)
                            {
                                Log.Error(ex);
                            }

                            client.BeginReceive(messageLength, receiveCount = 0, messageLength.Length, SocketFlags.None, receiveCallback, null);
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);

                            try
                            {
                                client.Shutdown(SocketShutdown.Both);
                                client.Close();
                            }
                            catch { }
                        }
                    };

                    client.BeginReceive(messageLength, 0, messageLength.Length, SocketFlags.None, receiveCallback, null);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
                finally
                {
                    _listenSocket.BeginAccept(acceptCallback, null);
                }
            };

            _listenSocket.BeginAccept(acceptCallback, null);

        }
Example #52
0
        //当有客户端连接时的处理
        public void OnConnectRequest(IAsyncResult ar)
        {
            //初始化一个SOCKET,用于其它客户端的连接
            server1 = (Socket)ar.AsyncState;
            Client = server1.EndAccept(ar);
            //将要发送给连接上来的客户端的提示字符串
            DateTimeOffset now = DateTimeOffset.Now;
              //      string strDateLine = "Welcome";

             //       Byte[] byteDateLine = System.Text.Encoding.UTF8.GetBytes(strDateLine);

            //将提示信息发送给客户端,并在服务端显示连接信息。
            remote = Client.RemoteEndPoint;

            showClientMsg(now.ToString("G") + Client.RemoteEndPoint.ToString() + "  Connected " + "\r\n");
             //       Client.Send(byteDateLine, byteDateLine.Length, 0);
            userListOperate(Client.RemoteEndPoint.ToString());

            //把连接成功的客户端的SOCKET实例放入哈希表
            _sessionTable.Add(Client.RemoteEndPoint, null);

            //等待新的客户端连接
            server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1);

            byte[] RevBuffer = new byte[1024];

            while (true)
            {
                int recv = Client.Receive(RevBuffer);
                string stringdata = Encoding.UTF8.GetString(RevBuffer, 0, recv);
                string ip = Client.RemoteEndPoint.ToString();
                //获取客户端的IP和端口
                if (stringdata == "STOP")
                {
                    //当客户端终止连接时
                    showClientMsg(now.ToString("G") + "-->" + ip + "  Disconnected " + "\r\n");
                    _sessionTable.Remove(Client.RemoteEndPoint);
                    break;
                }

                //显示客户端发送过来的信息
                showClientMsg(now.ToString("G") + "--> " + ip + " " + stringdata + "\r\n");

                string SeqNo = stringdata.Substring(0, 6);
                string BcrNo = stringdata.Substring(6, 1);
                string Flag = stringdata.Substring(7, 1);

                bool Result = HandleDatafromErp(SeqNo, BcrNo, Flag);

                string Msg = string.Format("{0}{1}", SeqNo, Result ? "1" : "0");

                Byte[] sendData = Encoding.UTF8.GetBytes(Msg);

                Client.Send(sendData, sendData.Length, 0);
            }
        }
Example #53
0
        internal void OnAcceptReceived(IAsyncResult ar)
        {
            System.Net.Sockets.Socket sman = (System.Net.Sockets.Socket)ar.AsyncState;

            if (sman != null)
            {
                System.Net.Sockets.Socket newsocket = null;
                try
                {
                    newsocket = sman.EndAccept(ar);
                }
                catch (System.ObjectDisposedException e)
                {
                    string strError = string.Format("Exception calling EndAccept {0}", e);
                    LogError(MessageImportance.Highest, "EXCEPTION", strError);
                    return;
                }
                catch (System.Exception eall)
                {
                    string strError = string.Format("Exception calling EndAccept - continueing {0}", eall);
                    LogError(MessageImportance.Highest, "EXCEPTION", strError);
                }

                /// Start a new accept
                try
                {
                    sman.BeginAccept(AcceptCallback, sman);
                }
                catch (SocketException e3) /// winso
                {
                    string strError = string.Format("Exception calling BeginAccept2 {0}", e3);
                    LogError(MessageImportance.Highest, "EXCEPTION", strError);
                }
                catch (ObjectDisposedException e4) // socket was closed
                {
                    string strError = string.Format("Exception calling BeginAccept2 {0}", e4);
                    LogError(MessageImportance.Highest, "EXCEPTION", strError);
                }
                catch (System.Exception eall)
                {
                    string strError = string.Format("Exception calling BeginAccept2 {0}", eall);
                    LogError(MessageImportance.Highest, "EXCEPTION", strError);
                }


                if (newsocket == null)
                {
                    return;
                }

                LogMessage(MessageImportance.Medium, "NEWCON", string.Format("Accepted new socket {0}", newsocket.Handle));
                /// look up the creator for this socket
                ///
                SocketCreator creator = (SocketCreator)this.m_SocketSet[sman];
                if (creator != null)
                {
                    SocketClient newclient = creator.AcceptSocket(newsocket, this.m_ConMgrParent);

                    try
                    {
                        m_ConMgrParent.FireAcceptHandler(newclient);
                    }
                    catch (System.Exception efire)
                    {
                        string strError = string.Format("Exception Fireing Acception Handler -{0}", efire);
                        LogError(MessageImportance.Highest, "EXCEPTION", strError);
                    }

                    newclient.DoAsyncRead();
                }
            }
        }
Example #54
0
        /// <summary>
        /// 客户端连接处理函数
        /// </summary>
        /// <param name="iar">欲建立服务器连接的Socket对象</param>
        protected virtual void AcceptConn(IAsyncResult iar)
        {
            try
            {
                //如果服务器停止了服务,就不能再接收新的客户端
                if (!this.ServerState)
                {
                    return;
                }

                //接受一个客户端的连接请求
                System.Net.Sockets.Socket oldserver = (System.Net.Sockets.Socket)iar.AsyncState;
                System.Net.Sockets.Socket client    = oldserver.EndAccept(iar);

                //检查是否达到最大的允许的客户端数目
                if (this.ClientCount >= this.DefaultMaxClient)
                {
                    //服务器已满,发出通知
                    if (ServerFull != null)
                    {
                        ServerFull("服务连接数已满");
                        //继续接收来自来客户端的连接
                        sock.BeginAccept(new AsyncCallback(AcceptConn), sock);
                        client.Close();
                        return;
                    }
                }

                //添加到连接存储器中
                Session s = new Session(client, ReceiveBufferSize);
                _SessionTable.Add(s.Id, s);

                if (ClientConn != null)
                {
                    ClientConn(s);
                }
                try
                {
                    //接着开始异步连接客户端
                    client.BeginReceive(s.ReceiveDataBuffer, 0, s.ReceiveDataBuffer.Length, SocketFlags.None,
                                        new AsyncCallback(ReceiveData), s);
                }
                catch (SocketException ex)
                {
                    if (ServerError != null)
                    {
                        ServerError("Fail-EX:客户端连接;ErrorCode:" + ex.ErrorCode + ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    if (ServerError != null)
                    {
                        ServerError("Fail-EX:客户端连接;" + ex.Message);
                    }
                }

                //继续接收来自来客户端的连接
                sock.BeginAccept(new AsyncCallback(AcceptConn), sock);
            }
            catch (Exception ex)
            {
                if (ServerError != null)
                {
                    ServerError("Fail-EX:客户端连接;" + ex.Message);
                }
            }
        }
Example #55
0
        private static void Main()
        {
            _server = new Socket(SocketType.Stream, ProtocolType.Tcp);
            _server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9111));
            _server.Listen(10);
            _server.BeginAccept(ar =>
                                {
                                    _server = _server.EndAccept(ar);

                                    _client = new Socket(SocketType.Stream, ProtocolType.Tcp);
                                    _client.BeginConnect("123.58.172.232", 9111, a =>
                                                                                 {
                                                                                     _client.EndConnect(a);

                                                                                     BeginReceiveServer((Socket) a.AsyncState);
                                                                                 }, _client);

                                    BeginReceiveClient(_server);
                                }, _server);

            while (_client.Connected)
                Thread.Sleep(1000);
        }
Example #56
0
 private static Task<Socket> AcceptAsync(Socket socket)
 {
     return Task.Factory.FromAsync((cb, state) => socket.BeginAccept(cb, state), ar => socket.EndAccept(ar), null);
 }
Example #57
0
        public void NetworkTargetTcpTest()
        {
            NetworkTarget target;

            target = new NetworkTarget()
            {
                Address = "tcp://127.0.0.1:3004",
                Layout = "${message}\n",
                KeepConnection = true,
            };

            string expectedResult = string.Empty;

            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                Exception receiveException = null;
                var resultStream = new MemoryStream();
                var receiveFinished = new ManualResetEvent(false);

                listener.Bind(new IPEndPoint(IPAddress.Loopback, 3004));
                listener.Listen(10);
                listener.BeginAccept(
                    result =>
                    {
                        try
                        {
                            Console.WriteLine("Accepting...");
                            byte[] buffer = new byte[4096];
                            using (Socket connectedSocket = listener.EndAccept(result))
                            {
                                Console.WriteLine("Accepted...");
                                int got;
                                while ((got = connectedSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0)
                                {
                                    Console.WriteLine("Got {0} bytes", got);
                                    resultStream.Write(buffer, 0, got);
                                }
                                Console.WriteLine("Closing connection...");
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Receive exception {0}", ex);
                            receiveException = ex;
                        }
                        finally
                        {
                            receiveFinished.Set();
                        }
                    }, null);

                target.Initialize(new LoggingConfiguration());

                int pendingWrites = 100;
                var writeCompleted = new ManualResetEvent(false);
                var exceptions = new List<Exception>();

                AsyncContinuation writeFinished =
                    ex =>
                    {
                        lock (exceptions)
                        {
                            Console.WriteLine("{0} Write finished {1}", pendingWrites, ex);
                            exceptions.Add(ex);
                            pendingWrites--;
                            if (pendingWrites == 0)
                            {
                                writeCompleted.Set();
                            }
                        }
                    };

                int toWrite = pendingWrites;
                for (int i = 0; i < toWrite; ++i)
                {
                    var ev = new LogEventInfo(LogLevel.Info, "logger1", "messagemessagemessagemessagemessage" + i).WithContinuation(writeFinished);
                    target.WriteAsyncLogEvent(ev);
                    expectedResult += "messagemessagemessagemessagemessage" + i + "\n";
                }

                Assert.IsTrue(writeCompleted.WaitOne(10000, false), "Writes did not complete");
                target.Close();
                Assert.IsTrue(receiveFinished.WaitOne(10000, false), "Receive did not complete");
                string resultString = Encoding.UTF8.GetString(resultStream.GetBuffer(), 0, (int)resultStream.Length);
                Assert.IsNull(receiveException, "Receive exception: " + receiveException);
                Assert.AreEqual(expectedResult, resultString);
            }
        }
Example #58
0
        public void ConnectionRenew()
        {
            //异步建立连接回调
            AccessAction = () =>
            {
                Invoke((MethodInvoker)delegate ()
                {
                    try
                    {
                        String friendIP = socket.communicateSocket.RemoteEndPoint.ToString();
                        if (MyAccessCharacter == AccessCharater.Host || MyAccessCharacter == AccessCharater.HostWatcher)
                        {
                            ServerSocket serversocket = (ServerSocket)socket;
                            Socket communicateSocket = serversocket.communicateSockets.Last();
                            friendIP = communicateSocket.RemoteEndPoint.ToString();
                            Thread thread = new Thread(new ThreadStart(delegate ()
                            {
                                serversocket.Receive(ReceiveAction, communicateSocket);
                            }));
                            thread.Start();

                            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                            //本机预使用的IP和端口
                            int port;
                            if (!Int32.TryParse(connection.textBox_Port.Text, out port))
                            {
                                port = 9050 + SocketFunc.ReConnectCount;
                                SocketFunc.ReConnectCount++;
                            }
                            else
                            {
                                port += SocketFunc.ReConnectCount;
                                SocketFunc.ReConnectCount++;
                            }
                            IPEndPoint serverIP = new IPEndPoint(IPAddress.Any, port);
                            //绑定服务端设置的IP
                            serverSocket.Bind(serverIP);
                            //设置监听个数
                            serverSocket.Listen(1);
                            //异步接收连接请求
                            serverSocket.BeginAccept(ar =>
                            {
                                serversocket.communicateSockets.Add(serverSocket.EndAccept(ar));
                                AccessAction();
                            }, null);
                            if (MyAccessCharacter == AccessCharater.Host)
                            {
                                if (Language == Language.Chinese)
                                {
                                    connection.labelConnectStatus.Text = "已连接。 空闲端口号:" + port.ToString();
                                }
                                else
                                {
                                    connection.labelConnectStatus.Text = "Connected. Valid port number: " + port.ToString();
                                }
                                connection.Portusing = port;
                                if (serversocket.communicateSockets.Count == 1)
                                {
                                    connection.connected = true;
                                    connection.Close();
                                    msgProcessor.SendSecret("MyName", new List<string> { Version.ToString(), DatabaseVer.ToString(), PlayerName }, "");
                                }
                                else
                                {
                                    msgProcessor.SendSecret("SetWatcher", new List<string> { Version.ToString(), DatabaseVer.ToString(), PlayerName, RivalName }, "");
                                }
                            }
                            else
                            {
                                connection.Portusing = port;
                                if (serversocket.communicateSockets.Count == 1)
                                {
                                    connection.connected = true;
                                    connection.Close();
                                    connection.labelConnectStatus.Text = "已有1位玩家连接。 空闲端口号:" + port.ToString();
                                    msgProcessor.SendSecret("SetPlayer1", new List<string> { Version.ToString(), DatabaseVer.ToString() }, "");
                                }
                                else if (serversocket.communicateSockets.Count == 2)
                                {
                                    msgProcessor.SendSecret("SetPlayer2", new List<string> { Version.ToString(), DatabaseVer.ToString(), ClientsNames[serversocket.communicateSockets[0]] }, "");
                                    connection.labelConnectStatus.Text = "中继连接中。 空闲端口号:" + port.ToString();
                                }
                                else
                                {
                                    msgProcessor.SendSecret("SetWatcher", new List<string> { Version.ToString(), DatabaseVer.ToString(), ClientsNames[serversocket.communicateSockets[0]], ClientsNames[serversocket.communicateSockets[1]] }, "");
                                    connection.labelConnectStatus.Text = "中继连接中。 空闲端口号:" + port.ToString();
                                }
                            }
                        }
                        else
                        {
                            ClientSocket serversocket = (ClientSocket)socket;
                            Socket communicateSocket = serversocket.communicateSocket;
                            friendIP = communicateSocket.RemoteEndPoint.ToString();
                            serversocket.Receive(ReceiveAction, communicateSocket);
                            TryConnect = true;
                        }
                    }
                    catch (Exception exp)
                    {
                        connection.Disconnect();
                        if (socket == null)
                        {
                            if (Language == Language.Chinese)
                            {
                                MessageBox.Show("无法连接到对手,请确认您输入的IP地址是否正确。\r\n如果您确定IP地址正确,请输入对手的端口号。", "无法连接");
                            }
                            else
                            {
                                MessageBox.Show("Please check your opponent's IP Address and port number.", "Connection failed.");
                            }
                        }
                        else
                        {
                            if (Language == Language.Chinese)
                            {
                                MessageBox.Show(exp.Message, "错误");
                            }
                            else
                            {
                                MessageBox.Show(exp.Message, "Error");
                            }
                        }
                        return;
                    }
                });
            };
            //异步接收消息回调
            ReceiveAction = (code, source) =>
            {
                textBoxMsgRcv.Invoke((MethodInvoker)delegate ()
                {
                    msgProcessor.Receive(code, source);
                });

            };
        }