当前位置: 首页>>代码示例>>C#>>正文


C# IWebSocketConnection.Close方法代码示例

本文整理汇总了C#中IWebSocketConnection.Close方法的典型用法代码示例。如果您正苦于以下问题:C# IWebSocketConnection.Close方法的具体用法?C# IWebSocketConnection.Close怎么用?C# IWebSocketConnection.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IWebSocketConnection的用法示例。


在下文中一共展示了IWebSocketConnection.Close方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OnOpenConnection

        private void OnOpenConnection(IWebSocketConnection socket)
        {
            var authCookie = socket.ConnectionInfo.Cookies[FormsAuthentication.FormsCookieName];

            Player player;

            if (authCookie == null || !TryCreatePlayer(authCookie, socket, out player))
            {
                socket.Close();
                return;
            }

            Guid gameGuid;

            if (Guid.TryParse(socket.ConnectionInfo.Path.Replace("", String.Empty), out gameGuid))
            {
                if (_games.Any(g => g.Id == gameGuid))
                {
                    _games.Single(g => g.Id == gameGuid).AddPlayer(player);
                }
            }
        }
开发者ID:djcsdy,项目名称:ZenMu,代码行数:22,代码来源:Storyteller.cs

示例2: OnConfig

        private void OnConfig(IWebSocketConnection socket)
        {
            var connection = new Connection(socket, _packetSerializer);

            socket.OnOpen += () => Connected(connection);
            socket.OnClose += () => Disconnected(connection);
            //socket.OnBinary += (data) => DataRecieved(client, data);
            socket.OnMessage += (message) =>
                {
                    try
                    {
                        IPacket packet = _packetSerializer.Deserialize(message);
                        PacketRecieved(connection, packet);
                    }
                    catch (IllegalPacketException exception)
                    {
                        // If someone sent a malformed packet, close out eventually
                        Logger.Instance.Warn("{0}", exception);
                        socket.Close();
                    }

                };
        }
开发者ID:Erikai,项目名称:OpenORPG,代码行数:23,代码来源:NetworkManager.cs

示例3: OnConnected

        private void OnConnected(IWebSocketConnection context)
        {
            if (UserList.Count < ClientLimit)
            {
                Debug.WriteLine($"OnConnected: {context.ConnectionInfo.Id}, {context.ConnectionInfo.ClientIpAddress}");

                UserList[context.ConnectionInfo.Id] = context;
            }
            else
            {
                Debug.WriteLine($"OverLimit, Closed: {context.ConnectionInfo.Id}, {context.ConnectionInfo.ClientIpAddress}");
                context.Close();
            }
        }
开发者ID:radioman,项目名称:WebRtc.NET,代码行数:14,代码来源:WebRTCServer.cs

示例4: OnReceive

        private void OnReceive(IWebSocketConnection context, string msg)
        {
            Debug.WriteLine($"OnReceive {context.ConnectionInfo.Id}: {msg}");

            if (!msg.Contains("command")) return; 

            if(UserList.ContainsKey(context.ConnectionInfo.Id))
            {
                JsonData msgJson = JsonMapper.ToObject(msg);
                string command = msgJson["command"].ToString();

                switch (command) 
                {
                    case offer:
                    {
                        if (UserList.Count <= ClientLimit && !Streams.ContainsKey(context.ConnectionInfo.Id))
                        {
                            var session = Streams[context.ConnectionInfo.Id] = new WebRtcSession();
                            {
                                using (var go = new ManualResetEvent(false))
                                {
                                    var t = Task.Factory.StartNew(() =>
                                    {
                                        ManagedConductor.InitializeSSL();

                                        using (session.WebRtc)
                                        {
                                            session.WebRtc.AddServerConfig("stun:stun.l.google.com:19302", string.Empty, string.Empty);
                                            session.WebRtc.AddServerConfig("stun:stun.anyfirewall.com:3478", string.Empty, string.Empty);
                                            session.WebRtc.AddServerConfig("stun:stun.stunprotocol.org:3478", string.Empty, string.Empty);
                                            //session.WebRtc.AddServerConfig("turn:127.0.0.1:444", "test", "test");

                                            var ok = session.WebRtc.InitializePeerConnection();
                                            if (ok)
                                            {
                                                go.Set();

                                                // does not work yet, javascript side works though ;/
                                                //session.WebRtc.CreateDataChannel("msgDataChannel");

                                                while (!session.Cancel.Token.IsCancellationRequested &&
                                                       session.WebRtc.ProcessMessages(1000))
                                                {
                                                    Debug.Write(".");
                                                }
                                                session.WebRtc.ProcessMessages(1000);
                                            }
                                            else
                                            {
                                                Debug.WriteLine("InitializePeerConnection failed");
                                                context.Close();
                                            }
                                        }
                                        
                                    }, session.Cancel.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

                                    if (go.WaitOne(9999))
                                    {
                                        session.WebRtc.OnIceCandidate += delegate (string sdp_mid, int sdp_mline_index, string sdp)
                                        {
                                            if (context.IsAvailable)
                                            {
                                                JsonData j = new JsonData();
                                                j["command"] = "OnIceCandidate";
                                                j["sdp_mid"] = sdp_mid;
                                                j["sdp_mline_index"] = sdp_mline_index;
                                                j["sdp"] = sdp;
                                                context.Send(j.ToJson());
                                            }
                                        };

                                        session.WebRtc.OnSuccessAnswer += delegate(string sdp)
                                        {
                                            if (context.IsAvailable)
                                            {
                                                JsonData j = new JsonData();
                                                j["command"] = "OnSuccessAnswer";
                                                j["sdp"] = sdp;
                                                context.Send(j.ToJson());
                                            }
                                        };

                                        session.WebRtc.OnFailure += delegate(string error)
                                        {
                                            Trace.WriteLine($"OnFailure: {error}");
                                        };

                                        session.WebRtc.OnError += delegate
                                        {
                                            Trace.WriteLine("OnError");
                                        };

                                        unsafe
                                        {
                                            session.WebRtc.OnFillBuffer += delegate (byte * frame_buffer, uint yuvSize)
                                            {
                                                OnFillBuffer(frame_buffer, yuvSize);
                                            };

                                            session.WebRtc.OnRenderRemote += delegate (byte* frame_buffer, uint w, uint h)
//.........这里部分代码省略.........
开发者ID:radioman,项目名称:WebRtc.NET,代码行数:101,代码来源:WebRTCServer.cs

示例5: MessageRPCClientConnection

        internal void MessageRPCClientConnection(IWebSocketConnection webSocket, string message, KeePassRPCService service)
        {
            KeePassRPCClientConnection connection = null;

            lock (_lockRPCClientManagers)
            {
                _lockRPCClientManagers.HeldBy = Thread.CurrentThread.ManagedThreadId;
                foreach (KeePassRPCClientManager manager in _RPCClientManagers.Values)
                {
                    foreach (KeePassRPCClientConnection conn in manager.CurrentRPCClientConnections)
                    {
                        if (conn.WebSocketConnection == webSocket)
                        {
                            connection = conn;
                            break;
                        }
                    }
                    if (connection != null)
                        break;
                }
            }

            if (connection != null)
                connection.ReceiveMessage(message, service);
            else
                webSocket.Close();
        }
开发者ID:PabloElPatron,项目名称:KeeFox,代码行数:27,代码来源:KeePassRPCExt.cs

示例6: OnMessage

        /// <summary>
        /// Method called when the WebSocket receives a message.
        /// </summary>
        /// <param name="socket">The client socket the message comes from.</param>
        /// <param name="message">The client message.</param>
        private void OnMessage(IWebSocketConnection socket, string message)
        {
            // Timestamp containing the current time with the pattern: 2012-07-06 19:04:23
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            // Get user id from receivedJSON object
            string uid = string.Empty;

            // The chat message object with the ts (timestamp), uid (user id) and msg (message) properties.
            ChatMessage chatMessage = new ChatMessage();

            try
            {
                if (this.connectedSockets.ContainsKey(socket))
                {
                    // Get the client user name
                    uid = this.connectedSockets[socket];

                    // Build the JSON object which will be send to all connected clients.
                    // It contains the current timestamp, the user name the message is 
                    // came from and finally the message itself.
                    chatMessage.ts = timestamp;
                    chatMessage.uid = uid;
                    chatMessage.msg = message;
                    FleckLog.Info("Msg rcv: " + uid + " @ " + timestamp + " => " + message);

                    // Socket already stored in connected sockets and send its user name. So send
                    // assembled JSON object to all connected clients.
                    foreach (KeyValuePair<Fleck.IWebSocketConnection, string> client in this.connectedSockets)
                    {
                        client.Key.Send(JsonConvert.SerializeObject(chatMessage));
                    }
                } 
                else
                {
                    // First message from the socket => message contains the client user name.
                    // Check now if user name is available. If not, add socket to the connected 
                    // sockets containing its user name.
                    if (!this.connectedSockets.ContainsValue(message))
                    {
                        // Store new connected client with its send user name to the connected sockets.
                        this.connectedSockets.Add(socket, message);
                        FleckLog.Info("Client <" + socket.ConnectionInfo.ClientIpAddress + "> set user name to <" + message + ">");
                    }
                    else
                    {
                        // Send client that the user name is already in use. The server now has
                        // to close the WebSocket to the client
                        chatMessage.ts = timestamp;
                        chatMessage.uid = message;
                        chatMessage.msg = "Error: the user name <" + message + "> is already in use!";

                        // Serialise ChatMessage object to JSON
                        socket.Send(JsonConvert.SerializeObject(chatMessage));
                        socket.Close();

                        // If socket is stored in connected sockets list, remove it
                        if (this.connectedSockets.ContainsKey(socket))
                        {
                            this.connectedSockets.Remove(socket);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // WebSocket could not be bind. E.g. if the socket is already in use.
                FleckLog.Error("Error opening WebSocket on <" + this.connectionInfo + ">. WebSocket maybe in use?");
                FleckLog.Error("Exception string: \n" + e.ToString());

                // Wait until key is pressed
                Console.ReadLine();

                // Close application
                System.Environment.Exit(-1);
            }
        }
开发者ID:rubengrb,项目名称:WebSocket-Chat-Server,代码行数:82,代码来源:WebSocketChatServer.cs

示例7: OnClient

        /// <summary>
        /// When a client is connected, bind all relevant events.
        /// </summary>
        /// <param name="Socket"></param>
        private void OnClient(IWebSocketConnection Socket)
        {
            // Handle new socket opens.
            Socket.OnOpen = () =>
            {
                Console.Error.WriteLine("[II] Repeater Open:   " + Socket.ConnectionInfo.ClientIpAddress + Socket.ConnectionInfo.Path);

                try
                {
                    // Extract repeater arguments from URL.
                    var sPath = Socket.ConnectionInfo.Path.ToLowerInvariant();
                    var dArgs = Regex.Matches(sPath, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => x.Groups[3].Value);

                    // Handle based on the available types.
                    if (sPath.StartsWith("/tuio"))
                    {
                        dSockets[Socket] = new TUIOForwarder(dArgs);
                    }
                    else if (sPath.StartsWith("/console"))
                    {
                        dSockets[Socket] = new ConsoleForwarder();
                    }
                    else if (sPath.StartsWith("/win7"))
                    {
                        dSockets[Socket] = new Win7Forwarder(dArgs);
                    }
                    else if (sPath.StartsWith("/win8"))
                    {
                        dSockets[Socket] = new Win8Forwarder(dArgs);
                    }
                    else if (sPath.StartsWith("/mouse"))
                    {
                        dSockets[Socket] = new MouseForwarder(dArgs);
                    }
                    else
                    {
                        throw new ArgumentException("Unsupported Repeater");
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e.Message);
                    Socket.Close();
                }
            };

            // Handle socket closures.
            Socket.OnClose = () =>
            {
                Console.Error.WriteLine("[II] Repeater Closed: " + Socket.ConnectionInfo.ClientIpAddress + Socket.ConnectionInfo.Path);

                // Clean up.
                IForwarder pOut;
                if (dSockets.TryRemove(Socket, out pOut))
                {
                    if (pOut != null)
                        pOut.Dispose();
                }
            };

            // Handle socket errors.
            Socket.OnError = (Exception e) =>
            {
                Console.WriteLine("[WW] Repeater Socket Error: " + e.Message);
                Socket.Close();
            };

            // Listen for socket commands.
            Socket.OnMessage = (string data) =>
            {
                // Parse the message out.
                var pMessage = TouchMessage.FromString(data);
                if (pMessage.Valid == false)
                {
                    //Console.Error.WriteLine("[WW] Touch Invalid: " + data);
                    return;
                }

                // Find the forwarder.
                IForwarder pFwd;
                if (dSockets.TryGetValue(Socket, out pFwd))
                {
                    if (pFwd != null)
                        pFwd.Forward(pMessage);
                }
            };
        }
开发者ID:HEInventions,项目名称:TouchBridge,代码行数:91,代码来源:Repeater.cs

示例8: OnAdd

 //Method Called when a new connection is opened to the socket server
 static void OnAdd(IWebSocketConnection conn)
 {
     try
       {
     //Send some data back to the client knows the connection is open and to prevent FF / Chrome issue with message sending
     conn.Send("OPEN");
     //Add the Socket to our list of connected sockets
     _connectedSockets.TryAdd(conn.ConnectionInfo.Id.ToString(), conn);
     //Debug messages
     if (_debugMessages) Console.WriteLine("Socket Connection Opened : " + conn.ConnectionInfo.ClientIpAddress);
       }//try
       catch (Exception ex)
       {
     //Do something with our exception
     HandleException(ex, conn);
     conn.Close(); //Connection issue so close to prevent issues
       }//catch
 }
开发者ID:rockpool,项目名称:LAB_IPTV,代码行数:19,代码来源:program.cs


注:本文中的IWebSocketConnection.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。