Пример #1
0
        public async System.Threading.Tasks.Task <string> ReadMsg(System.Threading.CancellationToken token)
        {
            System.Net.WebSockets.WebSocketReceiveResult res;
            ArraySegment <byte> buf = new ArraySegment <byte>();

            res = await cws.ReceiveAsync(buf, token);

            return(buf.ToString());
        }
Пример #2
0
        async void MessageProcesser()
        {
            //recv
            try
            {
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(1024 * 1024))
                {
                    byte[] buf = new byte[1024];
                    ArraySegment <byte> buffer = new ArraySegment <byte>(buf);
                    while (websocket.State == System.Net.WebSockets.WebSocketState.Open)
                    {
                        var _recv = websocket.ReceiveAsync(buffer, System.Threading.CancellationToken.None);
                        Task.WaitAll(_recv);
                        var recv = _recv.Result;

                        ms.Write(buf, 0, recv.Count);
                        if (recv.EndOfMessage)
                        {
                            var count = ms.Position;
                            ms.Position = 0;
                            var msg    = NetMessage.Unpack(ms);
                            var posend = ms.Position;
                            if (posend != count)
                            {
                                throw new Exception("error msg.");
                            }

                            //重置pos
                            ms.Position = 0;
                            await OnRecv(msg);// .onEvent(httpserver.WebsocketEventType.Recieve, websocket, bytes);
                        }
                        //Console.WriteLine("recv=" + recv.Count + " end=" + recv.EndOfMessage);
                    }
                }
            }
            catch (Exception err)
            {
                Console.CursorLeft = 0;

                Console.WriteLine("error on recv." + err.Message);
            }
            //disconnect
            try
            {
                await this?.OnDisconnect();
            }
            catch (Exception err)
            {
                Console.CursorLeft = 0;

                Console.WriteLine("error on disconnect." + err.Message);
            }
        }
Пример #3
0
        public async Task TestWithDifferentCloseResponse()
        {
            var webSocketUrl = new Uri($"{WebServerUrl.Replace("http", "ws")}close");

            using var clientSocket = new System.Net.WebSockets.ClientWebSocket();
            await clientSocket.ConnectAsync(webSocketUrl, default).ConfigureAwait(false);

            var buffer = new ArraySegment <byte>(new byte[8192]);
            var result = await clientSocket.ReceiveAsync(buffer, default).ConfigureAwait(false);

            Assert.IsTrue(result.CloseStatus.HasValue);
            Assert.IsTrue(result.CloseStatus == System.Net.WebSockets.WebSocketCloseStatus.InvalidPayloadData);
        }
Пример #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var socket = new System.Net.WebSockets.ClientWebSocket();
            var token  = new CancellationToken(false);

            socket.ConnectAsync(new Uri("ws://localhost:50000/testsample/test3/test2"), token).Wait();
            socket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes("heelo")), System.Net.WebSockets.WebSocketMessageType.Binary, false, token).Wait();
            var buffer = new ArraySegment <byte>(new byte[1024]);
            var result = socket.ReceiveAsync(buffer, token);

            result.Wait();
            Console.WriteLine(Encoding.UTF8.GetString(buffer.Array, 0, result.Result.Count));
            Console.ReadLine();
        }
Пример #5
0
        protected static async Task <string> ReadString(System.Net.WebSockets.ClientWebSocket ws)
        {
            var buffer = new ArraySegment <byte>(new byte[8192]);

            using var ms = new MemoryStream();
            System.Net.WebSockets.WebSocketReceiveResult result;

            do
            {
                result = await ws.ReceiveAsync(buffer, default);

                ms.Write(buffer.Array, buffer.Offset, result.Count);
            }while (!result.EndOfMessage);

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
Пример #6
0
        protected static async Task <string> ReadString(System.Net.WebSockets.ClientWebSocket ws)
        {
            var buffer = new ArraySegment <byte>(new byte[8192]);

#pragma warning disable IDE0067 // Object not disposed - Apparently VS2019 (16.4.2) doesn't understand "await using" yet.
            await using var ms = new MemoryStream();
#pragma warning restore IDE0067
            System.Net.WebSockets.WebSocketReceiveResult result;

            do
            {
                result = await ws.ReceiveAsync(buffer, default);

                ms.Write(buffer.Array !, buffer.Offset, result.Count);
            }while (!result.EndOfMessage);

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
Пример #7
0
        private static async Task <WebSocket> SetupClientToken(System.Net.WebSockets.ClientWebSocket socket)
        {
            if (socket.State == System.Net.WebSockets.WebSocketState.Connecting || socket.State == System.Net.WebSockets.WebSocketState.Open)
            {
                byte[] _buffer = new byte[BUFFER_SIZE];

                ArraySegment <byte> buffer = new ArraySegment <byte>(_buffer);

                var received = await socket.ReceiveAsync(buffer, CancellationToken.None);

                if (received.Count > 0)
                {
                    byte[] tokenBytes = new byte[received.Count];
                    Array.ConstrainedCopy(buffer.Array, 0, tokenBytes, 0, received.Count);
                    return(new WebSocket(socket, new RandomId(tokenBytes)));
                }
            }
            return(null);
        }
Пример #8
0
        private static async System.Threading.Tasks.Task Prototype201802084_1()
        {
            // todo We need exception handling here.

            {
                double dateTimeFrequencyToPhaseFrequencyRatio =
                    (double)System.TimeSpan.TicksPerSecond / (double)System.Diagnostics.Stopwatch.Frequency;
                long basePhase = System.Diagnostics.Stopwatch.GetTimestamp();
                long baseUtcDateTimeInTicks = System.DateTime.UtcNow.Ticks;
                basePhase = System.Diagnostics.Stopwatch.GetTimestamp();
                baseUtcDateTimeInTicks = System.DateTime.UtcNow.Ticks;

                var clientWebSocket = new System.Net.WebSockets.ClientWebSocket();
                //System.Threading.Tasks.Task task =
                await
                clientWebSocket.ConnectAsync
                    (new System.Uri
                    //(@"wss://ws-feed-public.sandbox.gdax.com"),
                        (@"wss://ws-feed.gdax.com"),
                    System.Threading.CancellationToken.None
                    );

                // todo ??? The caller really should do this if needed.
                // todo ??? But any method really should do this
                // todo ??? if after {await} it's not supposed to return to the synchronization context.
                //// todo Comment in other places where we don't call this.
                //.ConfigureAwait(false);
                //int timeSpanInMilliSeconds = System.Environment.TickCount;

                // todo Remember to call this even if the task already completed -- to rethrow any exceptions.
                // todo {task.Result} also waits, right?
                //task.Wait();

                //task.RunSynchronously();
                //timeSpanInMilliSeconds = System.Environment.TickCount - timeSpanInMilliSeconds;

                //>>>clientWebSocket.ReceiveAsync

                if (clientWebSocket.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    // todo Prototype subscribe/unsubscribe for 1 instrument at a time.

                    const string channelName =
                        //@"heartbeat";
                        //@"ticker";
                        @"level2";
                    //@"user";
                    //@"matches";
                    //@"full";

                    const string requestString =
                        //Newtonsoft.Json.JsonConvert.SerializeObject
                        //   ( new
                        //      {
                        //         type = "subscribe",
                        //         product_ids = new string[] { @"ETH-USD", @"ETH-EUR", },
                        //      }
                        //   );
                        "{" +
                        "\"type\":\"subscribe\"," +
                        "\"channels\":[{\"name\":\"" + channelName + "\",\"product_ids\":[\"BTC-USD\",\"BTC-EUR\"]}]" +
                        "}";

                    byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(requestString);
                    await clientWebSocket.SendAsync
                        (new System.ArraySegment <byte>(requestBytes),

                        // todo ??? Binary didn't work, right?
                        System.Net.WebSockets.WebSocketMessageType.Text,
                        //System.Net.WebSockets.WebSocketMessageType.Binary,

                        true,
                        System.Threading.CancellationToken.None
                        );

                    // todo This really doesn't need to be more than 16K, right?
                    var receiveBuffer = new System.ArraySegment <byte>(new byte[33 * 1024]);

                    for (bool isMessageBegin = true; ;)
                    {
                        if (clientWebSocket.State != System.Net.WebSockets.WebSocketState.Open)
                        {
                            System.Console.WriteLine(@"201802085");
                            break;
                        }
                        else
                        {
                        }

                        System.Net.WebSockets.WebSocketReceiveResult webSocketReceiveResult =
                            await clientWebSocket.ReceiveAsync(receiveBuffer, System.Threading.CancellationToken.None);

                        // todo ???
                        if (webSocketReceiveResult.Count <= 0)
                        {
                            System.Console.WriteLine(@"201802086");
                            break;
                        }
                        else
                        {
                        }

                        if (isMessageBegin)
                        {
                            isMessageBegin = false;
                            System.Console.WriteLine(',');
                            //System.Console.WriteLine();
                            long currentUtcDateTimeInTicks =
                                (long)((double)(ulong)(System.Diagnostics.Stopwatch.GetTimestamp() - basePhase) * dateTimeFrequencyToPhaseFrequencyRatio + 0.5) +
                                baseUtcDateTimeInTicks;
                            System.Console.Write
                                ((new System.DateTime(currentUtcDateTimeInTicks)).ToString(@"o", System.Globalization.DateTimeFormatInfo.InvariantInfo));
                        }
                        else
                        {
                        }

                        string string1 =
                            System.Text.Encoding.ASCII.GetString(receiveBuffer.Array, 0, webSocketReceiveResult.Count);
                        System.Console.Write(string1);

                        if (webSocketReceiveResult.MessageType == System.Net.WebSockets.WebSocketMessageType.Close)
                        {
                            System.Console.WriteLine(@"201802087");
                            break;
                        }
                        else
                        {
                        }

                        if (webSocketReceiveResult.EndOfMessage)
                        {
                            isMessageBegin = true;
                            //break;
                        }
                        else
                        {
                        }
                    }
                }
                else
                {
                    System.Console.WriteLine(@"201802088");
                }

                // todo ??? WebSocketState >= CloseSent

                clientWebSocket.Dispose();
            }

            StaticBool1_ = true;
        }
Пример #9
0
        public async void conectar(bool enBaseDatos = true)
        {
            try {
                await cliente.ConnectAsync(new Uri("ws://irc-ws.chat.twitch.tv"), cancellationToken);

                if (cliente.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    byte[]   bufferByte = new byte[6000];
                    int      estado     = 0;
                    string[] ESPERAS    = { ":tmi.twitch.tv 376 " + canal + " :>", ":End of /NAMES list" };
                    System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"(.*)\!(.*)@(.*)\.tmi\.twitch\.tv (PRIVMSG|PART) #(.*) :(.*)", System.Text.RegularExpressions.RegexOptions.RightToLeft);

                    ArraySegment <byte> buffer = new ArraySegment <byte>(bufferByte);
                    await cliente.SendAsync(new ArraySegment <byte>(arrayBytes("PASS oauth:" + oauth)), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken);

                    await cliente.SendAsync(new ArraySegment <byte>(arrayBytes("NICK " + canal)), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken);

                    //cliente.Options.
                    //a cliente.ReceiveAsync(buffer, cancellationToken);
                    //envioDatos.
                    System.Net.WebSockets.WebSocketReceiveResult resultado = await cliente.ReceiveAsync(buffer, cancellationToken);

                    while (cliente.State == System.Net.WebSockets.WebSocketState.Open)
                    {
                        string[] respuestas = arrayString(bufferByte, resultado.Count).Replace("\n", "\r").Replace("\r\r", "\r").Split('\r');
                        for (int i = 0; i < respuestas.Length; i++)
                        {
                            string respuesta = respuestas[i];
                            if (respuesta == ESPERAS[0])
                            {
                                estado++;
                            }
                            string mensaje = "";
                            if (respuesta.Length > 0)
                            {
                                switch (estado)
                                {
                                case 1:
                                    estado++;
                                    mensaje = "JOIN #" + canal;
                                    await cliente.SendAsync(new ArraySegment <byte>(arrayBytes(mensaje)), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken);

                                    break;
                                }
                                if (respuesta == "PING :tmi.twitch.tv")
                                {
                                    await cliente.SendAsync(new ArraySegment <byte>(arrayBytes("PONG :tmi.twitch.tv")), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken);
                                }
                                else
                                {
                                    if (estado > 0)
                                    {
                                        //System.Diagnostics.Trace.WriteLine(respuesta);
                                        //System.Diagnostics.Trace.WriteLine(toxicidad(respuesta));
                                        while (mensajesEnviar.Count > 0)
                                        {
                                            string mensajeTexto = "PRIVMSG #" + Configuracion.parametro("canal") + " :" + mensajesEnviar[0];
                                            await cliente.SendAsync(new ArraySegment <byte>(arrayBytes(mensajeTexto)), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken);

                                            mensajesEnviar.RemoveAt(0);
                                        }
                                        System.Text.RegularExpressions.Match coincidencias = regEx.Match(respuesta);
                                        if (coincidencias.Success)
                                        {
                                            string[] partes = regEx.GetGroupNames();
                                            //System.Text.RegularExpressions.Group grp

                                            /*foreach (string nombre in partes) {
                                             * System.Text.RegularExpressions.Group grp = coincidencias.Groups[nombre];
                                             * //Console.WriteLine("   {0}: '{1}'", name, grp.Value);
                                             * }*/
                                            System.Diagnostics.Trace.WriteLine((coincidencias.Groups["0"].Value));
                                            System.Diagnostics.Trace.WriteLine("" + (coincidencias.Groups["2"].Value) + " = " + (coincidencias.Groups["6"].Value));
                                            string aliasUsuario = coincidencias.Groups["2"].Value.ToLower();
                                            long   idUsuario    = -1;
                                            try {
                                                Datos usuarios = BD.consulta("select id,avatar from usuarios where alias='" + aliasUsuario + "'");
                                                if (usuarios.Length == 0)
                                                {
                                                    String avatar  = null;
                                                    JSON   usuario = infoUsuario(aliasUsuario);
                                                    try {
                                                        avatar = usuario["data"][0]["profile_image_url"].ToString();
                                                    } catch { }

                                                    int numeroAfectados = BD.ejecutar("insert into usuarios (alias, avatar, nombre, userID) values ('" + aliasUsuario + "'," + (avatar != null ? "'" + avatar + "'" : "null") + ",'" + usuario["data"][0]["display_name"].ToString() + "','" + usuario["data"][0]["id"].ToString() + "')");
                                                    if (numeroAfectados == 1)
                                                    {
                                                        idUsuario = BD.id;
                                                    }
                                                }
                                                else
                                                {
                                                    if (usuarios[0]["avatar"] == null || usuarios[0]["avatar"].ToString().Length == 0)
                                                    {
                                                        JSON   usuario = infoUsuario(aliasUsuario);
                                                        string avatar  = usuario["data"][0]["profile_image_url"].ToString();
                                                        BD.ejecutar("update usuarios set avatar='" + avatar + "' where alias='" + aliasUsuario + "'");
                                                    }
                                                    idUsuario = long.Parse(usuarios[0]["id"].ToString());
                                                }
                                                string texto      = coincidencias.Groups["6"].Value;
                                                double puntuacion = toxicidad(texto);

                                                texto = tratarMensaje(texto, puntuacion);
                                                if (enBaseDatos)
                                                {
                                                    try {
                                                        texto = texto.Replace("\"", "\\\"").Replace("'", "''");
                                                        BD.ejecutar("insert into mensajes (idEstado, idUsuario, mensaje,puntuacion) values (1," + idUsuario + ", '" + texto + "'," + puntuacion.ToString().Replace(",", ".") + ")");
                                                    }catch (Exception ex1) {
                                                        BD.ejecutar("insert into mensajes (idEstado, idUsuario, mensaje,puntuacion) values (1," + idUsuario + ", '" + aUTF8(texto) + "'," + puntuacion.ToString().Replace(",", ".") + ")");
                                                    }
                                                }
                                            } catch (Exception ex) {
                                                LOG.debug(ex.Message, "Conectar a twitch");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        resultado = await cliente.ReceiveAsync(buffer, cancellationToken);
                    }
                    //resultado.
                    //System.Diagnostics.Trace.WriteLine(arrayString(bufferByte));
                }
            } catch (Exception ex) {
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }
        }
Пример #10
0
        public async void conectarTopicos(bool enBaseDatos = true)
        {
            try {
                await clienteTopic.ConnectAsync(new Uri("wss://pubsub-edge.twitch.tv"), cancellationToken2);

                if (clienteTopic.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    byte[]   bufferByte = new byte[6000];
                    int      estado     = 0;
                    string[] ESPERAS    = { "{ \"type\": \"PONG\" }", ":End of /NAMES list" };
                    System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"(.*)\!(.*)@(.*)\.tmi\.twitch\.tv (PRIVMSG|PART) #(.*) :(.*)", System.Text.RegularExpressions.RegexOptions.RightToLeft);

                    ArraySegment <byte>        buffer = new ArraySegment <byte>(bufferByte);
                    System.Windows.Forms.Timer ping   = new System.Windows.Forms.Timer();
                    ping.Interval = 15000;
                    ping.Enabled  = true;
                    ping.Tick    += async(object sender, EventArgs e) => {
                        if (clienteTopic.State == System.Net.WebSockets.WebSocketState.Open)
                        {
                            await clienteTopic.SendAsync(new ArraySegment <byte>(arrayBytes("{\"type\":\"PING\"}")), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken2);
                        }
                        else
                        {
                            //await clienteTopic.CloseAsync();
                            await clienteTopic.ConnectAsync(new Uri("wss://pubsub-edge.twitch.tv"), cancellationToken2);

                            if (clienteTopic.State == System.Net.WebSockets.WebSocketState.Open)
                            {
                                await clienteTopic.SendAsync(new ArraySegment <byte>(arrayBytes("{\"type\":\"RECONNECT\"}")), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken2);
                            }
                        }
                    };

                    /*await cliente.SendAsync(new ArraySegment<byte>(arrayBytes("NICK " + canal)), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken);*/
                    await clienteTopic.SendAsync(new ArraySegment <byte>(arrayBytes("{\"type\":\"PING\"}")), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken2);

                    System.Net.WebSockets.WebSocketReceiveResult resultado = await clienteTopic.ReceiveAsync(buffer, cancellationToken2);

                    while (clienteTopic.State == System.Net.WebSockets.WebSocketState.Open)
                    {
                        string[] respuestas = arrayString(bufferByte, resultado.Count).Replace("\n", "\r").Replace("\r\r", "\r").Split('\r');
                        for (int i = 0; i < respuestas.Length; i++)
                        {
                            string respuesta = respuestas[i];
                            string mensaje   = "";
                            if (respuesta.Length > 0)
                            {
                                switch (estado)
                                {
                                case 0:
                                    estado++;
                                    mensaje = "{\"type\":\"LISTEN\",\"nonce\":\"\",\"data\":{\"topics\": [\"channel-bits-events-v2." + Configuracion.parametro("id_usuario") + "\",\"whispers." + Configuracion.parametro("id_usuario") + "\",\"channel-subscribe-events-v1." + Configuracion.parametro("id_usuario") + "\"],\"auth_token\": \"" + Configuracion.parametro("oauth") + "\"}}";
                                    await clienteTopic.SendAsync(new ArraySegment <byte>(arrayBytes(mensaje)), System.Net.WebSockets.WebSocketMessageType.Text, true, cancellationToken2);

                                    break;

                                case 1:
                                    if (respuesta != ESPERAS[0])
                                    {
                                        JSON respuestaJSON = new JSON();
                                        respuestaJSON.parse(respuesta);
                                        switch (respuestaJSON["type"].ToString())
                                        {
                                        case "MESSAGE":
                                            if (respuestaJSON["data"]["topic"].ToString() == "whispers." + Configuracion.parametro("id_usuario"))
                                            {
                                                string texto      = ((Entidad)respuestaJSON["data"]["message"])["body"].ToString();
                                                double puntuacion = toxicidad(texto);

                                                tratarMensaje(texto, puntuacion);
                                                if (enBaseDatos)
                                                {
                                                    BD.ejecutar("insert into mensajes (idEstado, idUsuario, mensaje,puntuacion) values (1,1, '" + texto.Replace("\"", "\\\"") + "'," + puntuacion.ToString().Replace(",", ".") + ")");
                                                }
                                            }
                                            break;
                                        }

                                        System.IO.File.AppendAllText("sucripcion.txt", respuesta + "\r\n");
                                    }

                                    break;
                                }
                            }
                        }
                        try {
                            resultado = await clienteTopic.ReceiveAsync(buffer, cancellationToken);
                        } catch (Exception ex1) {
                            System.Diagnostics.Trace.WriteLine(ex1.Message);
                        }
                    }
                    //resultado.
                    //System.Diagnostics.Trace.WriteLine(arrayString(bufferByte));
                }
            } catch (Exception ex) {
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }
        }
Пример #11
0
        private static async System.Threading.Tasks.Task Prototype201803072_1()
        {
            // todo We need exception handling here.

            {
                double dateTimeFrequencyToPhaseFrequencyRatio =
                    (double)System.TimeSpan.TicksPerSecond / (double)System.Diagnostics.Stopwatch.Frequency;
                long basePhase = System.Diagnostics.Stopwatch.GetTimestamp();
                long baseUtcDateTimeInTicks = System.DateTime.UtcNow.Ticks;
                basePhase = System.Diagnostics.Stopwatch.GetTimestamp();
                baseUtcDateTimeInTicks = System.DateTime.UtcNow.Ticks;

                var clientWebSocket = new System.Net.WebSockets.ClientWebSocket();
                await
                clientWebSocket.ConnectAsync
                    (new System.Uri
                        (@"wss://testnet.bitmex.com/realtime"),
                    //(@"wss://bitmex.com/realtime"),
                    System.Threading.CancellationToken.None
                    );

                // todo ??? The caller really should do this if needed.
                // todo ??? But any method really should do this
                // todo ??? if after {await} it's not supposed to return to the synchronization context.
                //// todo Comment in other places where we don't call this.
                //.ConfigureAwait(false);

                if (clientWebSocket.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    {
                        const string message       = @"GET/realtime";
                        string       nonceAsString = (++Nonce_).ToString();

                        // todo Use ASCII encoding everywhere.
                        byte[] signatureBytes =
                            hmacsha256
                                (System.Text.Encoding.UTF8.GetBytes(ApiKeySecret_),
                                System.Text.Encoding.UTF8.GetBytes(message + nonceAsString)
                                );

                        string           signatureString = ByteArrayToString(signatureBytes);
                        /*const*/ string requestString   =
                            "{" +
                            "\"op\":\"authKey\"," +
                            "\"args\":[\"" + ApiKeyId_ + "\"," + nonceAsString + ",\"" + signatureString + "\"]" +
                            "}";
                        byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(requestString);
                        await clientWebSocket.SendAsync
                            (new System.ArraySegment <byte>(requestBytes),
                            System.Net.WebSockets.WebSocketMessageType.Text,
                            true,
                            System.Threading.CancellationToken.None
                            );
                    }

                    if (clientWebSocket.State == System.Net.WebSockets.WebSocketState.Open)
                    {
                        {
                            const string subscriptionTopicName =
                                //@"quote:XBTUSD";
                                //@"trade:XBTUSD";
                                //@"orderBookL2:XBTUSD";
                                //@"instrument:XBTUSD";
                                //@"instrument";
                                //@"liquidation";
                                //@"quoteBin1m:XBTUSD";
                                @"order";

                            const string requestString =
                                "{" +
                                "\"op\":\"subscribe\"," +
                                "\"args\":[\"" + subscriptionTopicName + "\"]" +
                                "}";
                            byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(requestString);
                            await clientWebSocket.SendAsync
                                (new System.ArraySegment <byte>(requestBytes),

                                // todo ??? For GDAX binary didn't work, right?
                                System.Net.WebSockets.WebSocketMessageType.Text,
                                //System.Net.WebSockets.WebSocketMessageType.Binary,

                                true,
                                System.Threading.CancellationToken.None
                                );
                        }

                        // todo For GDAX this really doesn't need to be more than 16K, right?
                        var receiveBuffer = new System.ArraySegment <byte>(new byte[33 * 1024]);

                        for (bool isMessageBegin = true; ;)
                        {
                            if (clientWebSocket.State != System.Net.WebSockets.WebSocketState.Open)
                            {
                                System.Console.WriteLine(@"201802085");
                                break;
                            }
                            else
                            {
                            }

                            System.Net.WebSockets.WebSocketReceiveResult webSocketReceiveResult =
                                await clientWebSocket.ReceiveAsync(receiveBuffer, System.Threading.CancellationToken.None);

                            // todo Is this correct?
                            // todo Are these conditions equivalent?
                            if (webSocketReceiveResult.CloseStatus.HasValue || webSocketReceiveResult.Count <= 0)
                            {
                                System.Console.WriteLine(@"201802086");
                                break;
                            }
                            else
                            {
                            }

                            if (isMessageBegin)
                            {
                                isMessageBegin = false;
                                System.Console.WriteLine(',');
                                //System.Console.WriteLine();
                                long currentUtcDateTimeInTicks =
                                    (long)((double)(ulong)(System.Diagnostics.Stopwatch.GetTimestamp() - basePhase) * dateTimeFrequencyToPhaseFrequencyRatio + 0.5) +
                                    baseUtcDateTimeInTicks;
                                System.Console.Write
                                    ((new System.DateTime(currentUtcDateTimeInTicks)).ToString(@"o", System.Globalization.DateTimeFormatInfo.InvariantInfo));
                            }
                            else
                            {
                            }

                            // todo Preserve decoding state between decoding chunks.
                            string string1 =
                                System.Text.Encoding.ASCII.GetString(receiveBuffer.Array, 0, webSocketReceiveResult.Count);

                            System.Console.Write(string1);

                            if (webSocketReceiveResult.MessageType == System.Net.WebSockets.WebSocketMessageType.Close)
                            {
                                System.Console.WriteLine(@"201802087");
                                break;
                            }
                            else
                            {
                            }

                            if (webSocketReceiveResult.EndOfMessage)
                            {
                                isMessageBegin = true;
                                //break;
                            }
                            else
                            {
                            }
                        }
                    }
                    else
                    {
                        System.Console.WriteLine(@"201802088");
                    }
                }
                else
                {
                    System.Console.WriteLine(@"201804021");
                }

                // todo ??? WebSocketState >= CloseSent

                clientWebSocket.Dispose();
            }

            StaticBool1_ = true;
        }
        private void initializeConnections()
        {
            cleanupConnection();
            client    = new System.Net.WebSockets.ClientWebSocket();
            receiveTh = new Thread(() =>
            {
                byte[] buff = new byte[16384];
                ArraySegment <byte> segment = new ArraySegment <byte>(buff);
                CancellationToken rcvToken  = new CancellationToken(false);
                try
                {
                    while (client.State == System.Net.WebSockets.WebSocketState.Open)
                    {
                        var result = client.ReceiveAsync(segment, rcvToken).Result;

                        processInput(System.Text.Encoding.UTF8.GetString(buff, 0, result.Count));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error on websocket");
                    Console.WriteLine(ex);
                }

                Console.WriteLine("receive thread ending");
                //the socket aborted. this will be in charge of reinitializing the connection.
                initializeConnections();
            });
            receiveTh.IsBackground = true;
            receiveTh.Name         = "receive";
            int keepAlive = 50 * 1000;

            sendTh = new Thread(() =>
            {
                try
                {
                    int toSend = keepAlive;
                    while (client.State == System.Net.WebSockets.WebSocketState.Open)
                    {
                        //hack, release send package.

                        int sent = 0;
                        while (sent++ < 30 && sendQueue.Count > 0 && client.State == System.Net.WebSockets.WebSocketState.Open)
                        {
                            string current             = string.Empty;
                            CancellationToken outToken = new CancellationToken();
                            if (sendQueue.TryDequeue(out current))
                            {
                                client.SendAsync(new ArraySegment <byte>(System.Text.Encoding.UTF8.GetBytes(current))
                                                 , System.Net.WebSockets.WebSocketMessageType.Text,
                                                 true, outToken).Wait();
                            }
                        }
                        Thread.Sleep(10);
                        toSend -= 10;
                        if (toSend <= 0)
                        {
                            sendQueue.Enqueue("0");
                            toSend = keepAlive;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error on send th");
                    Console.WriteLine(ex);
                }
                Console.WriteLine("send thread ending");
            });
            sendTh.Name         = "send";
            sendTh.IsBackground = true;

            processInput = HandleHandshake;
            Uri targetURI           = new Uri(firebaseUrl + "?v=" + version + "&ns=" + dbName);
            CancellationToken token = new CancellationToken(false);

            client.ConnectAsync(targetURI, token).ContinueWith((t) =>
            {
                Console.WriteLine("Connected");
                receiveTh.Start();
                sendTh.Start();
            });
        }
Пример #13
0
        /// <summary>
        /// WebSocket工作
        /// </summary>
        public void WebSocketHandler()
        {
            int nMaxSize = 4096;
            Uri uri      = new Uri(Settings.wsUri);

            wsClient = new System.Net.WebSockets.ClientWebSocket();

            bIsWebSocketHandlerOn = true;
            while (bIsWebSocketHandlerOn)
            {
                try
                {
                    // WebSocket连接
                    wsClient.ConnectAsync(uri, System.Threading.CancellationToken.None).Wait();
                    while (wsClient.State == System.Net.WebSockets.WebSocketState.Open)
                    {
                        // 格式化心跳参数
                        if (!Settings.HeartBeatParams.Has("action"))
                        {
                            Settings.HeartBeatParams.Put("action", "AdSubAppHeartBeat");
                        }
                        if (!Settings.HeartBeatParams.Has("cpuId"))
                        {
                            //Settings.HeartBeatParams.Put("cpuId", Settings.CpuId);
                            Settings.HeartBeatParams.Put("cpuId", "666999");
                        }
                        if (!Settings.HeartBeatParams.Has("version"))
                        {
                            Settings.HeartBeatParams.Put("version", Settings.Version);
                        }

                        // 准备发送
                        byte[] tmpSendBuf = System.Text.Encoding.Default.GetBytes(Settings.HeartBeatParams.ToString().Replace("\r", "").Replace("\n", "").Replace(" ", ""));
                        var    sendBuf    = new ArraySegment <byte>(tmpSendBuf); // 发送缓冲区
                        wsClient.SendAsync(sendBuf, System.Net.WebSockets.WebSocketMessageType.Text, true, System.Threading.CancellationToken.None).Wait();
                        Settings.HeartBeatParams.Remove("lastCmd");
                        Settings.HeartBeatParams.Remove("errMsg");
                        tmpSendBuf = null;

                        // 准备接收
                        byte[] tmpRecvBuf = new byte[nMaxSize];
                        var    recvBuf    = new ArraySegment <byte>(tmpRecvBuf); // 接收缓冲区
                        wsClient.ReceiveAsync(recvBuf, System.Threading.CancellationToken.None).Wait();

                        // 解析数据
                        string recvMsg = System.Text.Encoding.Default.GetString(recvBuf.Array);
                        recvMsg    = recvMsg.Substring(0, recvMsg.IndexOf('\0'));
                        tmpRecvBuf = null;

                        // 解析心跳返回数据
                        //ParseHeartBeatResult(recvMsg);

                        System.Threading.Thread.Sleep(Settings.HeartBeatRate);
                        //MemoryCheck();
                    }
                }
                catch (Exception e)
                {
                    System.Console.WriteLine("WebSocket Exception: " + e.Message);
                    Settings.RuntimeLog.Severe("WebSocket Exception: " + e.ToString());
                }
            }
        }
        private async System.Threading.Tasks.Task RunClient(string url, IObserver <PIItemsStreamValues> observer, System.Threading.CancellationToken cancellationToken)
        {
            Uri uri = new Uri(url);

            System.Net.WebSockets.WebSocketReceiveResult receiveResult;
            byte[] receiveBuffer = new byte[65536];
            ArraySegment <byte> receiveSegment = new ArraySegment <byte>(receiveBuffer);

            using (System.Net.WebSockets.ClientWebSocket webSocket = new System.Net.WebSockets.ClientWebSocket())
            {
                if ((this.Configuration.ApiClient.Username == null) || (this.Configuration.ApiClient.Password == null))
                {
                    webSocket.Options.UseDefaultCredentials = true;
                }
                else
                {
                    webSocket.Options.Credentials = new System.Net.NetworkCredential(this.Configuration.ApiClient.Username, this.Configuration.ApiClient.Password);
                }

                try
                {
                    await webSocket.ConnectAsync(uri, System.Threading.CancellationToken.None);
                }
                catch (System.Net.WebSockets.WebSocketException e)
                {
                    Console.WriteLine("Could not connect to server.");
                    observer.OnError(e);
                    return;
                }
                while (true)
                {
                    try
                    {
                        receiveResult = await webSocket.ReceiveAsync(receiveSegment, cancellationToken);
                    }
                    catch (OperationCanceledException)
                    {
                        observer.OnCompleted();
                        break;
                    }

                    if (receiveResult.MessageType != System.Net.WebSockets.WebSocketMessageType.Text)
                    {
                        await webSocket.CloseAsync(
                            System.Net.WebSockets.WebSocketCloseStatus.InvalidMessageType,
                            "Message type is not text.",
                            System.Threading.CancellationToken.None);

                        observer.OnError(new Exception("Message type is not text."));
                        return;
                    }
                    else if (receiveResult.Count > receiveBuffer.Length)
                    {
                        await webSocket.CloseAsync(
                            System.Net.WebSockets.WebSocketCloseStatus.InvalidPayloadData,
                            "Message is too long.",
                            System.Threading.CancellationToken.None);

                        observer.OnError(new Exception("Message is too long."));
                        return;
                    }
                    try
                    {
                        string message             = System.Text.Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count);
                        PIItemsStreamValues values = Newtonsoft.Json.JsonConvert.DeserializeObject <PIItemsStreamValues>(message);
                        observer.OnNext(values);
                    }
                    catch (Exception e)
                    {
                        observer.OnError(e);
                    }
                }
                await webSocket.CloseAsync(
                    System.Net.WebSockets.WebSocketCloseStatus.NormalClosure,
                    "Closing connection.",
                    System.Threading.CancellationToken.None);

                observer.OnCompleted();
            }
        }
        public async void Connect(System.Threading.CancellationToken?token = null)
        {
            var _token = token ?? GetDefaultCancellationToken();

            if (ReceivedMessageFunc == null)
            {
                throw (new ArgumentNullException(nameof(ReceivedMessageFunc)));
            }

            Log(LogType.Info, "开始连接服务器");

            if (!this._isConnect)
            {
                clientWebSocket = new System.Net.WebSockets.ClientWebSocket();
            }
            else
            {
                throw new Exception("已经建立链接,请断开链接后再试");
            }
            await clientWebSocket.ConnectAsync(new Uri("ws://message.1688.com/websocket"), _token);

            var rr = System.Threading.Tasks.Task.Run(async() =>
            {
                while (_isConnect)
                {
                    try
                    {
                        var buffer = new ArraySegment <byte>(new byte[4096]);
                        var result = await clientWebSocket.ReceiveAsync(buffer, _token);
                        if (result.MessageType == System.Net.WebSockets.WebSocketMessageType.Text)
                        {
                            if (result.EndOfMessage)
                            {
                                var json            = System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                                var receivedMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <ReceivedMessage>(json, serializerSettings);
                                Log(LogType.Info, "接收到消息,类型:" + receivedMessage.Type);
                                if (receivedMessage.Type == WebSocketMessageType.CONNECT_ACK)
                                {
                                    IsConnect = true;
                                    sendHeartbeat(_token);
                                }
                                else if (receivedMessage.Type == WebSocketMessageType.SERVER_PUSH)
                                {
                                    var dd = System.Threading.Tasks.Task.Run(() =>
                                    {
                                        try
                                        {
                                            var b  = Newtonsoft.Json.JsonConvert.DeserializeObject <ReceivedMessageDataBaseType>(receivedMessage.Content, serializerSettings);
                                            var ss = GetReceivedMessageData(b.Type, receivedMessage.Content);
                                            var r  = ReceivedMessageFunc?.Invoke(receivedMessage.MsgSource, ss);
                                            if (r == true)
                                            {
                                                sendConfirm(receivedMessage, _token);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Log(LogType.Error, "处理消息异常", ex);
                                        }
                                    });
                                }
                                else if (receivedMessage.Type == WebSocketMessageType.SYSTEM)
                                {
                                    SystemInfoFunc?.Invoke(receivedMessage.MsgSource, receivedMessage.Content);
                                }
                                else
                                {
                                    Log(LogType.Error, "接收到其他消息,--------------------------------------------------类型:" + receivedMessage.Type);
                                    //throw new Exception("异常");
                                }
                            }
                            else
                            {
                                throw new Exception("异常");
                            }
                        }
                        else if (result.MessageType == System.Net.WebSockets.WebSocketMessageType.Binary)
                        {
                            throw new Exception("异常");
                        }
                        else if (result.MessageType == System.Net.WebSockets.WebSocketMessageType.Close)
                        {
                            throw new Exception("异常");
                        }
                        else
                        {
                            throw new Exception("异常");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log(LogType.Error, "接收数据异常", ex);
                        //throw new Exception("异常", ex);
                    }
                }
            });

            sendConnect(_token);
            //sendHeartbeat();
        }
Пример #16
0
        async void MessageProcesser()
        {
            //recv
            try
            {
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(1024 * 1024))
                {
                    byte[] buf = new byte[1024];
                    ArraySegment <byte> buffer = new ArraySegment <byte>(buf);
                    while (websocket.State == System.Net.WebSockets.WebSocketState.Open)
                    {
                        var recv = await websocket.ReceiveAsync(buffer, System.Threading.CancellationToken.None);

                        //Task.WaitAll(_recv);
                        //var recv = _recv.Result;

                        ms.Write(buf, 0, recv.Count);
                        if (recv.EndOfMessage)
                        {
                            var count = ms.Position;
                            ms.Position = 0;
                            var msg    = NetMessage.Unpack(ms);
                            var posend = ms.Position;
                            if (posend != count)
                            {
                                throw new Exception("error msg.");
                            }

                            //重置pos
                            ms.Position = 0;

                            var   iddata = msg.Params["_id"];
                            ulong id     = BitConverter.ToUInt64(iddata, 0);
                            if (mapRecv.TryRemove(id, out OnClientRecv onRecvOnce))
                            {
                                await onRecvOnce(msg);
                            }
                            else
                            {
                                await OnRecv(msg);// .onEvent(httpserver.WebsocketEventType.Recieve, websocket, bytes);
                            }
                        }
                        //Console.WriteLine("recv=" + recv.Count + " end=" + recv.EndOfMessage);
                    }
                }
            }
            catch (Exception err)
            {
                Console.CursorLeft = 0;

                Console.WriteLine("error on recv." + err.Message);
            }
            //disconnect
            try
            {
                await this?.OnDisconnect();
            }
            catch (Exception err)
            {
                Console.CursorLeft = 0;

                Console.WriteLine("error on disconnect." + err.Message);
            }
            finally
            {
                this.Connected = false;
            }
        }