Close() публичный Метод

public Close ( ) : void
Результат void
Пример #1
0
	// 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();
	}
Пример #2
0
    /// <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();
    }
Пример #3
0
        public override void ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
        {
            string description;

            if (!session.ProtocolProcessor.VerifyHandshake(session, commandInfo, out description))
            {
                session.Close(session.ProtocolProcessor.CloseStatusCode.ProtocolError, description);
                return;
            }

            session.OnHandshaked();
        }
Пример #4
0
	public WsClient () {

		bool success = TestConnection();
		if (success) {
			Debug.Log ("Server check ok");
			string server = String.Format("wss://{0}:{1}/",  ip,  port );
			using (conn = new WebSocket (server,"game"));
			conn.Connect ();

			conn.OnOpen += (sender, e) => conn.Send ("Server Connected");

			conn.OnError += (sender, e) => {
				Debug.Log("Websocket Error");
				conn.Close ();
			};

			conn.OnClose += (sender, e) => {
				Debug.Log("Websocket Close");
				conn.Close ();
			};
		} else {
			Debug.Log ("Server check failed");
			return;
		}

		conn.SslConfiguration.ServerCertificateValidationCallback =
			(sender, certificate, chain, sslPolicyErrors) => {
			// Do something to validate the server certificate.
			Debug.Log ("Cert: " + certificate);

			return true; // If the server certificate is valid.
		};



	}
Пример #5
0
        public override void ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
        {
            //Close handshake was sent from client side, now got a handshake response
            if (session.StateCode == WebSocketStateConst.Closing)
            {
                session.CloseWithoutHandshake();
                return;
            }

            //Got server side closing handshake request, send response now
            var statusCode = commandInfo.CloseStatusCode;

            if (statusCode <= 0)
                statusCode = session.ProtocolProcessor.CloseStatusCode.NoStatusCode;

            session.Close(statusCode, commandInfo.Text);
        }
Пример #6
0
	// Use this for initialization
	IEnumerator Start () {
        WebSocket w = new WebSocket(new Uri("ws://192.168.1.206:8888/ws"));
		yield return StartCoroutine(w.Connect());
		w.SendString("UnityTest");
		int i=0;
		while (true)
		{
			string reply = w.RecvString();
			if (reply != null)
			{
				Debug.Log ("Received: "+reply);
                w.SendString("UnityTest " + i++);
			}
			if (w.Error != null)
			{
				Debug.LogError ("Error: "+w.Error);
				break;
			}
			yield return 0;
		}
		w.Close();
	}
Пример #7
0
        public override void ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
        {
            //Close handshake was sent from client side, now got a handshake response
            if (session.State == WebSocketState.Closing)
            {
                //Not NormalClosure
                if (commandInfo.CloseStatusCode != session.ProtocolProcessor.CloseStatusCode.NormalClosure &&
                    (commandInfo.CloseStatusCode > 0 || !string.IsNullOrEmpty(commandInfo.Text)))
                {
                    session.FireError(new Exception(string.Format("{0}: {1}", commandInfo.CloseStatusCode, commandInfo.Text)));
                }
                session.CloseWithouHandshake();
                return;
            }

            //Got server side closing handshake request, send response now
            var statusCode = commandInfo.CloseStatusCode;

            if (statusCode <= 0)
                statusCode = session.ProtocolProcessor.CloseStatusCode.NoStatusCode;

            session.Close(statusCode, commandInfo.Text);
        }
Пример #8
0
 // Use this for initialization
 IEnumerator Start()
 {
     WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:3000"));
     yield return StartCoroutine(w.Connect());
     w.SendString("Hi there");
     int i = 0;
     while(true)
     {
         string reply = w.RecvString();
         if(reply != null)
         {
             Debug.Log("Received: " + reply);
             w.SendString("Hi there" + i++);
         }
         if(w.Error != null)
         {
             Debug.LogError("Error: " + w.Error);
             break;
         }
         yield return 0;
     }
     w.Close();
 }
Пример #9
0
        private static void Main(string[] args)
        {
            var client = new WebSocket("127.0.0.1", 8080);
            client.Opened += (sender, eventArgs) => Console.WriteLine("Connection open!");
            client.Closed += (sender, eventArgs) => Console.WriteLine("Connection closed");
            client.MessageReceived += (sender, eventArgs) => Console.WriteLine(((WebSocketEventArgs)eventArgs).Data);

            var exit = false;

            while (!exit)
            {
                var cmd = Console.ReadLine();

                switch (cmd)
                {
                    case "/close":
                        client.Close();
                        break;
                    case "/exit":
                        exit = true;
                        break;
                    case "/open":
                        client.Open();
                        break;
                    case "/send":
                        client.SendMdnString();
                        break;
                    default:
                        Console.WriteLine("Unknown command " + cmd);
                        break;
                }
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
Пример #10
0
    // Use this for initialization
    IEnumerator Start()
    {
        WebSocket w = new WebSocket(new Uri("ws://178.62.242.126:8000/"));
        yield return StartCoroutine(w.Connect());
        int i=0;
        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                float newAccelerationTarget = parseAcceleration(reply);
                if(newAccelerationTarget > 0.1f){

                    accelerationTargetReached = false;
                    accelerationTarget = 1.0f;
                }

                moveCharacter();
                Debug.Log ("Received: "+reply);
            }
            if (w.Error != null)
            {
                Debug.LogError ("Error: "+w.Error);
                break;
            }
            yield return 0;
        }
        w.Close();
    }
    // Use this for initialization
    IEnumerator StartWebSocket_CR()
    {
        WebSocket w = new WebSocket(new Uri("ws://128.2.236.66:3000"));
        yield return StartCoroutine(w.Connect());

		w.SendString("Ctrl Connected");
        while (true)
        {
            string res = w.RecvString();
			if (res != null)
            {
#if UNITY_EDITOR
                Debug.Log("Received: " + res);
#endif
                //w.SendString("Hi there" + i++);
                char[] delimiterChars = { ' ' ,'\t' };
				string[] parseStr = res.Split(delimiterChars);

				switch(parseStr[0]){
					case "m+":{
					_crowdSim.globalAttentionMean = SetValueFromString(_crowdSim.globalAttentionMean, true, parseStr);
						break;
					}
					case "m-":{
					_crowdSim.globalAttentionMean = SetValueFromString(_crowdSim.globalAttentionMean, false, parseStr);
						break;
					}
					case "d+":{
					_crowdSim.globalAttentionStDev = SetValueFromString(_crowdSim.globalAttentionStDev, true, parseStr);
						break;
					}
					case "d-":{
						_crowdSim.globalAttentionStDev = SetValueFromString(_crowdSim.globalAttentionStDev, false, parseStr);
						break;
					}
					case "u+":{
						_crowdSim.seatPosAttentionUpper = SetValueFromString(_crowdSim.seatPosAttentionUpper, true, parseStr);
						break;
					}
					case "u-":{
						_crowdSim.seatPosAttentionUpper = SetValueFromString(_crowdSim.seatPosAttentionUpper, false, parseStr);
						break;
					}
					case "l+":{
						_crowdSim.seatPosAttentionLower = SetValueFromString(_crowdSim.seatPosAttentionLower, true, parseStr);
						break;
					}
					case "l-":{
						_crowdSim.seatPosAttentionLower = SetValueFromString(_crowdSim.seatPosAttentionLower, false, parseStr);
						break;
					}

				}
			
				w.SendString("|Unity> currStat: m=" + _crowdSim.globalAttentionMean + ", dev=" + _crowdSim.globalAttentionStDev 
				             + ", A_up=" + _crowdSim.seatPosAttentionUpper + ", A_Low=" +  _crowdSim.seatPosAttentionLower + "." );

				
				//w.SendString("|Unity> blar blar" + res);

            }
            if (w.Error != null)
            {
#if UNITY_EDITOR
                Debug.Log("Error: " + w.Error);
#endif
                break;
            }
            yield return 0;
        }
        w.Close();
    }
        /// <summary>
        /// Subscribes to the provided <paramref name="outgoing"/> stream, sending all events to the provided <paramref name="socket"/>.
        /// </summary>
        /// <param name="outgoing">The outgoing stream.</param>
        /// <param name="socket">
        /// The socket.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/> which will complete when either the observable completes (or errors) or the socket is closed (or errors).
        /// </returns>
        private static async Task OutgoingMessagePump(IObservable<string> outgoing, WebSocket socket)
        {
            var completion = new TaskCompletionSource<int>();
            var subscription = new IDisposable[] { null };

            Action complete = () =>
            {
                subscription[0]?.Dispose();
                completion.TrySetResult(0);
            };

            // Until the socket is closed, pipe messages to it, then complete.
            subscription[0] = outgoing.TakeWhile(_ => !socket.IsClosed).SelectMany(
                next => socket.Send(ResponseKind.Next + next).ToObservable(),
                error => socket.Send(ResponseKind.Error + JsonConvert.SerializeObject(error.ToDetailedString())).ToObservable(),
                () =>
                {
                    if (socket.IsClosed)
                    {
                        return Observable.Empty<Unit>();
                    }

                    // Send and close the socket.
                    var send = socket.Send(ResponseKind.Completed.ToString(CultureInfo.InvariantCulture)).ToObservable();
                    return send.SelectMany(_ => socket.Close((int)WebSocketCloseStatus.NormalClosure, "onCompleted").ToObservable());
                }).Subscribe(_ => { }, _ => complete(), complete);
            await completion.Task;
        }
Пример #13
0
        private static void ListenToMtgox()
        {
            var ws = new WebSocket("ws://" + Dns.GetHostAddresses("websocket.mtgox.com").First().ToString() + ":80/mtgox", "*");
            var observableWs = new ObservableWebsocket(ws);

            if (!ws.Connect())
            {
                Console.WriteLine("Not connected");
                Console.ReadLine();
            }
            else
            {
                Console.Clear();
                Connected(observableWs);
                ws.Close();
            }
        }
Пример #14
0
    // Use this for initialization
    IEnumerator Start () {
		w = new WebSocket(new Uri("ws://ec2-54-213-60-9.us-west-2.compute.amazonaws.com:16248"));
        w.OnError += OnError;
        w.OnLogMessage += OnLogMessage;
        Debug.Log("Trying to connect");
        yield return StartCoroutine(w.Connect());
        Debug.Log(w.isConnected ? "Connected!" : "Couldn't connect");
		while (true) {
            if (w.lastError != null)
                break;
            var reply = w.Recv();
            if (reply != null) {
                //var stringData = "[";
                //for (var i = 0; i < reply.Length; ++i)
                //{
                //    if (i % 4 == 0)
                //        stringData += "\n";
                //    var c = reply[i];
                //    stringData += " " + c.ToString("000");
                //}
                //stringData += " ]";
                //Debug.Log("Received from the server: " + stringData);
                uint spec = BitConverter.ToUInt32(reply, 0);
                switch (spec) {
                    case specInitialize:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            player.id = id;
                            uint otherPlayerCount = BitConverter.ToUInt32(reply, 8);
                            int byteIndex = 12;
                            for (int i = 0; i < otherPlayerCount; ++i)
                            {
                                var other = new Player();
                                other.id = BitConverter.ToUInt32(reply, byteIndex);
                                other.name = Encoding.Unicode.GetString(reply, byteIndex + 4, nameLength);
                                float x = BitConverter.ToSingle(reply, byteIndex + nameLength + 4);
                                float y = BitConverter.ToSingle(reply, byteIndex + nameLength + 8);
                                float z = BitConverter.ToSingle(reply, byteIndex + nameLength + 12);
                                other.pos = new Vector3(x, y, z);
                                other.health = BitConverter.ToSingle(reply, byteIndex + nameLength + 16);
                                otherPlayers[other.id] = other;
                                byteIndex += 4 + nameLength + 16;
                            }
                            Debug.Log("Received ID: " + id + " and game start info.  There are " + otherPlayerCount + " other players.");
                            if (onGameInfoReceived != null)
                                onGameInfoReceived(id, otherPlayers);
                            break;
                        }
                    case specDisconnect:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            Player other = null;
                            if (otherPlayers.TryGetValue(id, out other))
                            {
                                Debug.Log(other.name + " disconnected.");
                                if (onPlayerDisconnected != null)
                                    onPlayerDisconnected(other);
                            } else
                                Debug.Log("player" + id + " disconnected.");
                            otherPlayers.Remove(id);
                            break;
                        }
                    case specAnnounceConnect:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            if (id == player.id)
                                break;
                            Player other = new Player();
                            other.id = id;
                            other.name = Encoding.Unicode.GetString(reply, 8, nameLength);
                            float x = BitConverter.ToSingle(reply, 8 + nameLength);
                            float y = BitConverter.ToSingle(reply, 12 + nameLength);
                            float z = BitConverter.ToSingle(reply, 16 + nameLength);
                            other.pos = new Vector3(x, y, z);
                            otherPlayers[id] = other;
                            Debug.Log(other.name + " has connected (id " + other.id + ", pos " + other.pos + ")");
                            if (onPlayerConnected != null)
                                onPlayerConnected(other);
                            break;
                        }
                    case specUpdatePosition:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            float x = BitConverter.ToSingle(reply, 8);
                            float y = BitConverter.ToSingle(reply, 12);
                            float z = BitConverter.ToSingle(reply, 16);
                            var pos = new Vector3(x, y, z);
                            Player other = null;
                            if (player.id == id)
                                break;
                            if (otherPlayers.TryGetValue(id, out other)) {
                                //Debug.Log(other.name + " is now at position " + pos);
                                other.pos = pos;
                                if (onPlayerMoved != null)
                                    onPlayerMoved(other);
                            }
                            break;
                        }
                    case specMessage:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            string message = Encoding.Unicode.GetString(reply, 8, reply.Length - 8);
                            string name = null;
                            if (id == player.id)
                                name = player.name;
                            if (name == null) {
                                Player other = null;
                                if (otherPlayers.TryGetValue(id, out other)) {
                                    name = other.name;
                                    if (onPlayerMessage != null)
                                        onPlayerMessage(other, message);
                                }
                            }
                            if (name != null)
                                Debug.Log(name + ": " + message);
                            else
                                Debug.Log("player" + id + ": " + message);
                            break;
                        }
                    case specHeartbeat:
                        {
                            SendHeartbeatResponse();
                            break;
                        }
                    case specUpdateHealth:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            float health = BitConverter.ToSingle(reply, 8);
                            Player updatedPlayer = null;
                            if (id == player.id)
                            {
                                updatedPlayer = player;
                            } else
                            {
                                Player other = null;
                                if (otherPlayers.TryGetValue(id, out other))
                                {
                                    updatedPlayer = other;
                                }
                            }
                            if (updatedPlayer != null)
                            {
                                updatedPlayer.health = health;
                                if (onPlayerUpdateHealth != null)
                                    onPlayerUpdateHealth(updatedPlayer, health);
                            }
                            break;
                        }
                    case specUpdateState:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            int stateSize = reply.Length - 8;
                            byte[] state = new byte[stateSize];
                            Buffer.BlockCopy(reply, 8, state, 0, stateSize);
                            Player updatedPlayer = null;
                            if (id == player.id) {
                                updatedPlayer = player;
                            } else {
                                Player other = null;
                                if (otherPlayers.TryGetValue(id, out other)) {
                                    updatedPlayer = other;
                                }
                            }
                            if (updatedPlayer != null) {
                                updatedPlayer.state = state;
                                if (onPlayerUpdateState != null)
                                    onPlayerUpdateState(updatedPlayer, state);
                            }
                            break;
                        }
                }
            } else {
                yield return 0;
            }
		}
		w.Close();
	}
Пример #15
0
    /// Use this for initialization
    IEnumerator StartCommunicator()
    {
        WebSocket w = new WebSocket(new Uri("ws://192.168.33.138:8080"));
        if(!testLocally) {
            yield return StartCoroutine(w.Connect());
            w.SendString("Hi there, I'm the communicator");
        }
        int i=0;
        while (true)
        {
            sendingIntervalCountdown -= Time.deltaTime;
            if(sendingIntervalCountdown < 0) {
                sendingIntervalCountdown = sendingInterval;
                String toSend = "{\"x\":"+ball.position.x+",\"y\":"+ball.position.z+",\"z\":"+ball.position.y+"}";
                Debug.Log(toSend);
                if(!testLocally) {
                    w.SendString (toSend);
                }
            }
            string reply = null;
            if(!testLocally) {
                reply = w.RecvString();
            } else {
                reply = localTestCommand;
                localTestCommand = null;
            }
            if (reply != null)
            {
                Debug.Log ("Received: "+reply);
                Vector3 force = Vector3.zero;
                /*if(reply != null && reply.Length == ) {
                    if(reply[0] == '#') {

                    }
                }*/
                switch(reply) {
                case "jump":
                    force = new Vector3(0, 300, 0);
                    break;
                case "left":
                    force = new Vector3(500, 0, 0);
                    break;
                case "right":
                    force = new Vector3(-500, 0, 0);
                    break;
                case "forward":
                    force = new Vector3(0, 0, 500);
                    break;
                case "backward":
                    force = new Vector3(0, 0, -500);
                    break;
                case "color":
                    force = new Vector3(0, 0, -500);
                    break;
                }
                //Debug.Log (force);
                ball.GetComponent<Rigidbody>().AddForce(force);
                //w.SendString("Hi there"+i++);
            }
            if (!testLocally && w.error != null)
            {
                Debug.LogError ("Error: "+w.error);
                break;
            }
            yield return 0;
        }
        w.Close();
    }
Пример #16
0
 // Call this second client to actually send random commands.
 IEnumerator StartGenerateData()
 {
     WebSocket w = new WebSocket(new Uri("ws://192.168.33.138:8080"));
     if(!testLocally) {
         yield return StartCoroutine(w.Connect());
         w.SendString("Hi there, I'm the random generator");
     }
     int i=0;
     while (true)
     {
         String[] elements = {"jump", "left", "right", "forward", "backward"};
         String randomElem = elements[UnityEngine.Random.Range(0,elements.Length)];
         Debug.Log(randomElem);
         if(!testLocally) {
             w.SendString(randomElem);
         } else {
             localTestCommand = randomElem;
         }
         if (!testLocally && w.error != null)
         {
             Debug.LogError ("Error: "+w.error);
             break;
         }
         yield return new WaitForSeconds(1f);
     }
     w.Close();
 }