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


C# WebSocket类代码示例

本文整理汇总了C#中WebSocket的典型用法代码示例。如果您正苦于以下问题:C# WebSocket类的具体用法?C# WebSocket怎么用?C# WebSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: Connect

    void Connect()
    {
        ws =  new WebSocket("ws://socket.nappers.jp:8888");

        // called when websocket messages come.
        ws.OnMessage += (sender, e) =>
        {
            string s = e.Data;
            Debug.Log(string.Format( "Receive {0}",s));
            messages.Add("> " + e.Data);
            if(messages.Count > 10){
                messages.RemoveAt(0);
            }
        };

        ws.OnError += (sender, e) =>
        {
            Debug.Log("OnError");
        };
        ws.OnClose += (sender, e) =>
        {
            Debug.Log("OnClose");

        };
        ws.OnOpen += (sender, e) =>
        {
            Debug.Log("OnOpen");

        };

        ws.Connect();
        Debug.Log("Connect to " + ws.Url);
    }
开发者ID:ryuusinnca,项目名称:unity_socketIO,代码行数:33,代码来源:Chat.cs

示例2: HttpListenerWebSocketContext

   internal HttpListenerWebSocketContext(
 HttpListenerContext context, Logger logger)
   {
       _context = context;
         _stream = WsStream.CreateServerStream (context);
         _websocket = new WebSocket (this, logger ?? new Logger ());
   }
开发者ID:uken,项目名称:websocket-sharp,代码行数:7,代码来源:HttpListenerWebSocketContext.cs

示例3: SendCloseHandshake

        public override void SendCloseHandshake(WebSocket websocket, int statusCode, string closeReason)
        {
            int size = (string.IsNullOrEmpty(closeReason) ? 0 : Encoding.UTF8.GetMaxByteCount(closeReason.Length)) + 2;

            byte[] playloadData = new byte[size];

            int highByte = statusCode / 256;
            int lowByte = statusCode % 256;

            playloadData[0] = (byte)highByte;
            playloadData[1] = (byte)lowByte;

            // don't send close handshake now because the connection was closed already
            if (websocket.State == WebSocketState.Closed)
                return;

            if (!string.IsNullOrEmpty(closeReason))
            {
                int bytesCount = Encoding.UTF8.GetBytes(closeReason, 0, closeReason.Length, playloadData, 2);
                SendDataFragment(websocket, OpCode.Close, playloadData, 0, bytesCount + 2);
            }
            else
            {
                SendDataFragment(websocket, OpCode.Close, playloadData, 0, playloadData.Length);
            }
        }
开发者ID:wiyonoaten,项目名称:WebSocket4Net,代码行数:26,代码来源:DraftHybi10Processor.cs

示例4: Start

    /// <summary>
    /// Start the Birb Client.
    /// </summary>
    /// <returns>Nothing right now.</returns>
    IEnumerator Start()
    {
        gameStateManager = GetComponent<GameStateManager>();
        Uri server = new Uri("ws://birb.herokuapp.com");
        Uri localhost = new Uri("ws://localhost:5000");
        socket = new WebSocket(server);
        callbacks = new Dictionary<BirbMessageCode, Callback>();
        yield return StartCoroutine(socket.Connect());
        int i = 0;

        // Testing
        //RunUnitTests();

        while (true)
        {
            string reply = socket.RecvString();
            if (reply != null)
            {
                Debug.Log("Received: " + reply);
                Process(reply);
            }
            if (socket.Error != null)
            {
                Debug.LogError("Error: " + socket.Error);
                break;
            }
            yield return 0;
        }
        socket.Close();
    }
开发者ID:UpBeet,项目名称:mating-ritual-client,代码行数:34,代码来源:BirbClient.cs

示例5: Connect

    // -----------------------------------------------------------------
    /// <summary>
    ///
    /// </summary>
    void Connect()
    {
        ws = new WebSocket (WSAddress);

        ws.OnOpen += (sender, e) => {
            Debug.Log ("<color=lime>WebSocket Open</color>");
        };

        ws.OnMessage += (sender, e) => {

            lock (messageQueue.SyncRoot) {
                try {
                    messageQueue.Enqueue (e.Data.ToString ());
                } catch (System.Exception ex) {
                    Debug.Log (ex.ToString ());
                }
            }

            //Debug.Log ("<color=cyan>WebSocket Message Type: " + e.Type + ", Data: " + e.Data + "</color>");
        };

        ws.OnError += (sender, e) => {
            Debug.Log ("<color=red>WebSocket Error Message: " + e.Message + "</color>");
        };

        ws.OnClose += (sender, e) => {
            Debug.Log ("<color=orange>WebSocket Close</color>");
        };

        ws.Connect ();
    }
开发者ID:nmbakfm,项目名称:hachitaiTeamLab,代码行数:35,代码来源:WebSocketClient.cs

示例6: Connect

    void Connect()
    {
        //接続
        //ポートの指定はしなくても大丈夫だった。80で接続してるはず。
        ws =  new WebSocket(url);

        ws.OnOpen += (sender, e) => {
            //接続したら自分を制御用PCとしてサーバーに教える
            //SendSetPCMessage();
            print("Connected");
        };
        ws.OnMessage += (sender, e) => {
            string s = e.Data;
            //Debug.Log (s);
            Dictionary<string, object> dict = Json.Deserialize (s) as Dictionary<string, object>;
            //Debug.Log (dict["power"].GetType() );
            long val = (long)dict["power"];
            //Debug.Log ("val="+val);
            toColor = GetColor(val/divBy);

            value =  val/divBy;
        };
        ws.Connect();

        ws.OnClose += (sender, e) => {
            print("Closed");
        };

        ws.OnError += (sender, e) => {
            print("Error : " + e.Message);
        };
    }
开发者ID:shinobushiva,项目名称:Takeakari-System,代码行数:32,代码来源:WebSocketConnect.cs

示例7: Connect

        public override bool Connect()
        {
            //bool baseOk = base.Connect();
            //if (!baseOk)
            //{
            //    return false;
            //}


            State = PhotonSocketState.Connecting;

            if (websocketConnectionObject != null)
            {
                UnityEngine.Object.Destroy(websocketConnectionObject);
            }

            websocketConnectionObject = new GameObject("websocketConnectionObject");
            MonoBehaviour mb = websocketConnectionObject.AddComponent<MonoBehaviour>();
            // TODO: not hidden for debug
            //websocketConnectionObject.hideFlags = HideFlags.HideInHierarchy;
            UnityEngine.Object.DontDestroyOnLoad(websocketConnectionObject);

            this.sock = new WebSocket(new Uri(ServerAddress));
            mb.StartCoroutine(this.sock.Connect());

            mb.StartCoroutine(ReceiveLoop());
            return true;
        }
开发者ID:ly774508966,项目名称:IUILab_Lecture_KinectAndOculusWithUnity3D,代码行数:28,代码来源:SocketWebTcp.cs

示例8: InitWebSocket

 void InitWebSocket()
 {
     _ws = new WebSocket ("wss://echo.websocket.org/");
     _ws.OnMessage += MessageCallback;
     _ws.OnError += ErrorCallback;
     _ws.Connect ();
 }
开发者ID:oldones,项目名称:app2pence,代码行数:7,代码来源:WebSocketImpl.cs

示例9: Play

        public void Play()
        {
            var uri = new Uri(Server + "?user=" + Uri.EscapeDataString(UserName));

            using (var socket = new WebSocket(uri))
            {
                socket.Connect();

                while (!ShouldExit)
                {
                    var response = socket.Recv();

                    if (!response.StartsWith(ResponsePrefix))
                    {
                        Console.WriteLine("Something strange is happening on the server... Response:\n{0}", response);
                        ShouldExit = true;
                    }
                    else
                    {
                        var boardString = response.Substring(ResponsePrefix.Length);

                        var action = DoMove(new GameBoard(boardString));

                        socket.Send(action);
                    }
                }
            }
        }
开发者ID:alhenk,项目名称:snake,代码行数:28,代码来源:BombermanBase.cs

示例10: Start

    void Start() {
        ws = new WebSocket("ws://echo.websocket.org");

        ws.OnOpen += OnOpenHandler;
        ws.OnMessage += OnMessageHandler;
        ws.OnClose += OnCloseHandler;

        stateMachine.AddHandler(State.Running, () => {
            new Wait(this, 3, () => {
                ws.ConnectAsync();
            });
        });

        stateMachine.AddHandler(State.Connected, () => {
            stateMachine.Transition(State.Ping);
        });

        stateMachine.AddHandler(State.Ping, () => {
            new Wait(this, 3, () => {
               ws.SendAsync("This WebSockets stuff is a breeze!", OnSendComplete);
            });
        });

        stateMachine.AddHandler(State.Pong, () => {
            new Wait(this, 3, () => {
                ws.CloseAsync();
            });
        });

        stateMachine.Run();
    }
开发者ID:rjansen,项目名称:unity-ws-demo,代码行数:31,代码来源:StatefulMain.cs

示例11: WebSocketFrame

        public WebSocketFrame(WebSocket webSocket, WebSocketFrameTypes type, byte[] data, UInt64 pos, UInt64 length, bool isFinal, bool useExtensions)
        {
            this.Type = type;
            this.IsFinal = isFinal;
            this.UseExtensions = useExtensions;

            if (data != null)
            {
                this.Data = new byte[length];
                Array.Copy(data, (int)pos, this.Data, 0, (int)length);
            }
            else
                data = NoData;

            // First byte: Final Bit + Rsv flags + OpCode
            byte finalBit = (byte)(IsFinal ? 0x80 : 0x0);
            this.Header = (byte)(finalBit | (byte)Type);

            if (this.UseExtensions && webSocket != null && webSocket.Extensions != null)
            {
                for (int i = 0; i < webSocket.Extensions.Length; ++i)
                {
                    var ext = webSocket.Extensions[i];
                    if (ext != null)
                    {
                        this.Header |= ext.GetFrameHeader(this, this.Header);
                        this.Data = ext.Encode(this);
                    }
                }
            }
        }
开发者ID:JohnMalmsteen,项目名称:mobile-apps-tower-defense,代码行数:31,代码来源:WebSocketFrame.cs

示例12: VerifyHandshake

        public override bool VerifyHandshake(WebSocket websocket, WebSocketCommandInfo handshakeInfo, out string description)
        {
            var challenge = handshakeInfo.Data;

            if (challenge.Length != challenge.Length)
            {
                description = m_Error_ChallengeLengthNotMatch;
                return false;
            }

            for (var i = 0; i < m_ExpectedChallenge.Length; i++)
            {
                if (challenge[i] != m_ExpectedChallenge[i])
                {
                    description = m_Error_ChallengeNotMatch;
                    return false;
                }
            }

            if (!handshakeInfo.Text.ParseMimeHeader(websocket.Items))
            {
                description = m_Error_InvalidHandshake;
                return false;
            }

            description = string.Empty;
            return true;
        }
开发者ID:ByteSempai,项目名称:Ubiquitous,代码行数:28,代码来源:DraftHybi00Processor.cs

示例13: Start

	// Use this for initialization
	IEnumerator Start () {
		WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:8080/websocket"));
		yield return StartCoroutine(w.Connect());

		int i = 0;
		w.SendString(PackMessage("Hi there", i));
		while (true)
		{
			string reply = w.RecvString();
			if (reply != null)
			{
				Message msg = UnpackMessage (reply);
				Debug.Log ("Received: " + msg.msg + ", " + msg.no);
				w.SendString (PackMessage ("Hi there", i));
			}
			if (w.error != null)
			{
				Debug.LogError ("Error: " + w.error);
				break;
			}

			++i;

			yield return 0;
		}
		w.Close();
	}
开发者ID:rex8312,项目名称:WebsocketExample,代码行数:28,代码来源:EchoTest.cs

示例14: WebSocketRequestHandler

        /// <summary>
        /// Returns a handler for incoming Web stream requests.
        /// </summary>
        /// <param name="route">
        /// The handler.
        /// </param>
        /// <param name="controller">
        /// The controller.
        /// </param>
        /// <param name="args">
        /// The request parameters.
        /// </param>
        /// <returns>
        /// A handler for incoming Web stream requests.
        /// </returns>
        public static Func<IDictionary<string, object>, Task> WebSocketRequestHandler(
            this ControllerRoute route,
            object controller,
            IDictionary<string, string> args)
        {
            return async environment =>
            {
                using (var socket = new WebSocket(environment))
                {
                    Task incomingMessagePump;
                    Func<string, IObservable<string>> getObservable;
                    if (route.ObservableParameters != null)
                    {
                        // Route has observable parameters.
                        var observableParams = route.ObservableParameters.ToDictionary(_ => _, _ => new SingleSubscriptionObservable());
                        getObservable = name => observableParams[name].Observable;
                        incomingMessagePump = IncomingMessagePump(socket, observableParams);
                    }
                    else
                    {
                        // No observable parameters.
                        getObservable = _ => Observable.Empty<string>();
                        incomingMessagePump = Task.FromResult(0);
                    }

                    // Hook up the incoming and outgoing message pumps.
                    var outgoing = GetObservableFromHandler(() => route.Invoke(controller, args, getObservable));
                    var outgoingMessagePump = OutgoingMessagePump(outgoing, socket);

                    // Close the socket when both pumps finish.
                    await Task.WhenAll(outgoingMessagePump, incomingMessagePump);
                }
            };
        }
开发者ID:WebStreams,项目名称:WebStreams.Server,代码行数:49,代码来源:ControllerRouteExtensions.cs

示例15: Start

        IEnumerator Start()
        {
            _game = gameObject.GetComponent<MainProxy>();

            _state = ConnectionState.UNKNOWN;
            _socket = new WebSocket (new Uri ("ws://188.242.130.83:3000/echo"));
            yield return StartCoroutine (_socket.Connect ());
        }
开发者ID:andi2,项目名称:ld32-6,代码行数:8,代码来源:Connection.cs


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