コード例 #1
0
        /// <summary>
        ///     Denne metode håndterer kommunikation mellem clienten og serverens på asynkron vis.
        /// </summary>
        public void AcceptCallback(IAsyncResult asyncResult)
        {
            //Her laves en lokal variable af typen socket, den deklareres her fordi at socketens scope skal persistere udenfor try catch kaldet lige under.
            Socket tempSocket;

            //Her forsøges der at placerer en client socket på lokal variablen.
            try {
                //Server socketen benytter sig at funktionen som opretter en socket instans som placeres på lokal variablen uden for try catchens scope.
                tempSocket = ServerSocket.EndAccept(asyncResult);
            }
            //Hvis objektet ikke længere eksisterer kastes objectdisposedexceptionen. I tilfælde af det ikke lykkedes at oprette en forbindelse på den lokale socket.
            catch (ObjectDisposedException x)
            //Denne exception bliver kastet når at der bliver forsøgt at blive gjort noget på et objekt som allerede er skillet af med.
            {
                Debug.WriteLine(x);
                return;
            }

            lock (ClientSocket) {
                //I dette kald bliver den nyoprettet client socket tilføjet til serverens clientsocket liste.
                ClientSocket.Add(tempSocket);
            }

            //Her begynder den nyoprettet socket at modtage information fra clientens socket.
            tempSocket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None
                                    /* TODO - Gå hjem og find ud af hvad singlecast og multicast er*/, ReceiveCallBack, tempSocket);
            Debug.WriteLine("Client forbundet, venter på input");

            //Serverens socket kalder beginaccept rekusivt for hele tiden at se om der er nye data og forbindelser mellem client socketen og serverens socket.
            ServerSocket.BeginAccept(AcceptCallback, null);
        }
コード例 #2
0
ファイル: SocketListener.cs プロジェクト: Profilan/Matco
 private void SetupServer()
 {
     ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Port));
     ServerSocket.Listen(0);
     ServerSocket.BeginAccept(AcceptCallback, null);
     ServerListening?.Invoke("Server listening on port " + Port);
 }
コード例 #3
0
        private void StartServer()
        {
            ServerSocket.Bind(TcpEndPoint);
            ServerSocket.Listen(10);

            ServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), ServerSocket);
        }
コード例 #4
0
        // This is the call back function, which will be invoked when a client is connected
        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object
                Socket      clientSocket = ServerSocket.EndAccept(asyn);
                AsyncClient asyncClient  = new AsyncClient(clientSocket);
                Clients.Add(asyncClient);
                AsyncClientsDict.Add(clientSocket, asyncClient);

                ClientConnected(this, new ServerClientEventArgs(asyncClient));

                // Let the worker Socket do the further processing for the
                // just connected client
                WaitForData(clientSocket);
                // Now increment the client count

                // Since the main Socket is now free, it can go back and wait for
                // other clients who are attempting to connect
                ServerSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (Exception ex)
            {
                ServerException(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #5
0
        private void AcceptCallback(IAsyncResult ar)
        {
            Socket listener = (Socket)ar.AsyncState;
            Socket handler  = listener.EndAccept(ar);

            StateObject state = new StateObject();

            state.workSocket = handler;

            PersonId++;

            Person person = new Person();

            JsonContainer jsonContainer = new JsonContainer()
            {
                CurrentPersonId = new CurrentPersonId(),
                Messages        = new System.Collections.ObjectModel.ObservableCollection <MessageContent>(),
                Persons         = new List <Person>()
            };

            MessageContent messageContent = new MessageContent();

            Connect connect = new Connect(PersonId, person, jsonContainer, messageContent, _uIViewModel);

            connect.FirstTime = true;

            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(connect.ReadCallback), state);
            ReadDone.WaitOne();

            ServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), listener);
        }
コード例 #6
0
ファイル: Sock.cs プロジェクト: 2010phenix/RemoteDesktop-1
 public void Start(int port, int backlog)
 {
     if (!ServerSocket.Connected)
     {
         ServerSocket.Bind(new IPEndPoint(IPAddress.Any, port));
         ServerSocket.Listen(backlog);
         ServerSocket.BeginAccept(new AsyncCallback(OnAccept), ServerSocket);
     }
 }
コード例 #7
0
 /// <summary>
 /// Метод асинхронного принятия новых подключений
 /// </summary>
 /// <param name="result"></param>
 private void AcceptCallback(IAsyncResult result)
 {
     lock (locker)
     {
         if (IsListeningStatus != false)
         {
             ConnectionValue connection = new ConnectionValue();
             try
             {
                 // Завершение операции Accept
                 connection.Socket     = ServerSocket.EndAccept(result);
                 connection.SocketID   = connection.Socket.Handle;
                 connection.Buffer     = new byte[SizeBuffer];
                 connection.RemoteIP   = ((IPEndPoint)connection.Socket.RemoteEndPoint).Address.ToString();
                 connection.RemotePort = ((IPEndPoint)connection.Socket.RemoteEndPoint).Port;
                 lock (Сonnections) Сonnections.Add(connection);
                 // Начало операции Receive и новой операции Accept
                 connection.Socket.BeginReceive(connection.Buffer,
                                                0, connection.Buffer.Length, SocketFlags.None,
                                                new AsyncCallback(ReceiveCallback),
                                                connection);
                 //Сообщаем о новом подключении
                 CallConnected(connection);
             }
             catch (SocketException exc)
             {
                 CallErrorServer(Sockets.ServerErrorType.AcceptError, exc.Message + exc.ToString());
                 CloseConnection(connection);
             }
             catch (Exception exc)
             {
                 CallErrorServer(Sockets.ServerErrorType.AcceptError, exc.Message + exc.ToString());
                 CloseConnection(connection);
             }
             finally
             {
                 try
                 {
                     if (ServerSocket != null && ServerSocket.IsBound)
                     {
                         ServerSocket?.BeginAccept(new AsyncCallback(AcceptCallback), null);
                     }
                 }
                 catch (Exception ex)
                 {
                     CallErrorServer(Sockets.ServerErrorType.AcceptError, ex.Message + ex.ToString());
                 }
             }
         }
     }
 }
コード例 #8
0
ファイル: Sock.cs プロジェクト: 2010phenix/RemoteDesktop-1
        private void OnAccept(IAsyncResult ar)
        {
            Socket sock = ServerSocket.EndAccept(ar);

            Sock.Client client = new Sock.Client(sock, DataBuffer.Length);
            client.EncryptionKey      = EncryptionKey;
            client.EncryptionSettings = EncryptionSettings;
            client.UseEncryption      = UseEncryption;

            if (OnClientAccepted != null)
            {
                OnClientAccepted(client);
            }

            client.ClientSocket.BeginReceive(DataBuffer, 0, DataBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), client);

            ServerSocket.BeginAccept(new AsyncCallback(OnAccept), sock);
        }
コード例 #9
0
ファイル: SocketListener.cs プロジェクト: Profilan/Matco
        private void AcceptCallback(IAsyncResult ar)
        {
            Socket socket;

            try
            {
                socket = ServerSocket.EndAccept(ar);
            }
            catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
            {
                return;
            }

            ClientSockets.Add(socket);
            socket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket);
            // Console.WriteLine("Client connected, waiting for request...");
            ClientConnected?.Invoke();
            ServerSocket.BeginAccept(AcceptCallback, null);
        }
コード例 #10
0
 private void AcceptNextPendingConnection()
 {
     try
     {
         ServerSocket.BeginAccept(OnAcceptCallback, null);
         OnReportingStatus(StatusCode.Info, "Started accepting new TCP connection");
     }
     catch (ObjectDisposedException)
     {
     }
     catch (SocketException socketException)
     {
         OnCaughtException(socketException, EventCode.Accept);
     }
     catch (Exception exception)
     {
         OnCaughtException(exception, EventCode.Other);
     }
 }
コード例 #11
0
        //开启服务
        private void BtnOpenServer_Click(object sender, EventArgs e)
        {
            try
            {
                if (radioBtnchooseTCP.Checked == true)//选择建立TCP
                {
                    ServerSocket = new Socket(AddressFamily.InterNetwork,
                                              SocketType.Stream,
                                              ProtocolType.Tcp);
                }
                if (radioBtnchooseUDP.Checked == true)//选择建立UDP
                {
                    ServerSocket = new Socket(AddressFamily.InterNetwork,
                                              SocketType.Dgram,
                                              ProtocolType.Udp);
                }

                IP   = IPBox.Text;
                Port = Convert.ToInt32(PortBox.Text);

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

                //Bind and listen on the given address
                ServerSocket.Bind(ipEndPoint);
                ServerSocket.Listen(8080);

                //Accept the incoming clients
                ServerSocket.BeginAccept(new AsyncCallback(OnAccept), ServerSocket);

                BtnOpenServer.Enabled  = false;
                BtnCloseServer.Enabled = true;

                //DebugLog.Debug("socket监听服务打开");
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "error",MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine(ex.Message + "---" + DateTime.Now.ToLongTimeString() + "出错信息:" + "\n");
                //DebugLog.Debug(ex);
            }
        }
コード例 #12
0
        private void AcceptCallback(IAsyncResult AR)
        {
            lock (lockAccept)
            {
                Socket socket;

                try
                {
                    socket = ServerSocket.EndAccept(AR);
                    var session = new SocketSession(socket, BufferSize);

                    ClientSockets.Add(session);

                    socket.BeginReceive(session.SessionStorage, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket);
                    ServerSocket.BeginAccept(AcceptCallback, null);
                }
                catch (Exception ex) // I cannot seem to avoid this (on exit when properly closing sockets)
                {
                    LogController.WriteLog(new ServerLog("*** ERROR ***: \n" + ex.Message, ServerLogType.ERROR));
                }
            }
        }
コード例 #13
0
        public void Start(bool waitForUserTypeExit = true)
        {
            if (Started)
            {
                throw new Exception("Server already has been started.");
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();

            Initialize();
            ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Port));

            ServerSocket.Listen(0);
            ServerSocket.BeginAccept(AcceptCallback, null);
            Started = true;
            ServerStarted?.Invoke();
            RunServerStartupTasks();
            sw.Stop();
            LogController.WriteLog(new ServerLog($"Server started in {sw.ElapsedMilliseconds}ms", "Server", "Start"));
            LogController.WriteLog(new ServerLog($"Running at port {Port}"));
            Console.WriteLine("Type 'exit' to stop; 'reboot' to send reboot request event...");
            string line = "";

            if (waitForUserTypeExit)
            {
                while (line != "exit")
                {
                    line = Console.ReadLine();
                    if (line == "reboot")
                    {
                        RebootRequest?.Invoke();
                    }
                }
            }
        }
コード例 #14
0
 /// <summary>
 /// Запуск сервера
 /// </summary>
 /// <param name="port">порт сервера для прослушивания</param>
 public void Start(int port)
 {
     lock (locker)
     {
         Port = port;
         try
         {
             if (SetupServerSocket())
             {
                 ServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), ServerSocket);
                 IsListeningStatus = true;
                 CallStatus(ServerStatus.Start);
             }
             else
             {
                 CallErrorServer(ServerErrorType.StartListenError, "Failed to create socket");
             }
         }
         catch (Exception exс)
         {
             CallErrorServer(ServerErrorType.StartListenError, exс.Message);
         }
     }
 }
コード例 #15
0
 /// <summary>
 /// Opens the port and start accepting connections
 /// </summary>
 public void Start()
 {
     Debug("Opening Socket...", DebugParams);
     ServerSocket.BeginAccept(new AsyncCallback(OnClientAccept), null);
 }
コード例 #16
0
 private void AcceptClient()
 {
     ServerSocket.BeginAccept(ClientJoined, ServerSocket);
 }