Пример #1
0
        private static void HandleHttpRequest(WebSocketsClient client, Dictionary <string, string> headers)
        {
            //var uri = headers["GET"];
            //var origin = headers["Origin"];

            var key = client.ResolveKey(headers["Sec-WebSocket-Key"]);

            var answer = Convert.ToBase64String(Encoding.ASCII.GetBytes(key.Value));

            var sendHeaders = new List <string>
            {
                "HTTP/1.1 101 Switching Protocols",  //
                "Connection: Upgrade",               //
                "Sec-WebSocket-Accept: " + answer,   //
                "Upgrade: websocket"                 //
            };

            Send(client, String.Join("\r\n", sendHeaders) + "\r\n\r\n", false, false, (c, d) => client.Start());

            if (!CMOptions.ModuleDebug)
            {
                return;
            }

            CMOptions.ToConsole("HEADERS>>>\n");
            CMOptions.ToConsole(sendHeaders.ToArray());
        }
Пример #2
0
        private static void Send(
            WebSocketsClient client,
            string data,
            bool encode,
            bool compress,
            Action <WebSocketsClient, byte[]> callback)
        {
            VitaNexCore.TryCatch(
                () =>
            {
                int len;
                byte[] buffer;

                if (encode)
                {
                    Encode(data, out buffer, out len);
                }
                else
                {
                    buffer = data.Select(c => (byte)c).ToArray();
                    len    = buffer.Length;
                }

                Send(client, buffer, len, compress, callback);
            },
                CMOptions.ToConsole);
        }
Пример #3
0
        private static void Send(
            WebSocketsClient client,
            byte[] buffer,
            int len,
            bool compress,
            Action <WebSocketsClient, byte[]> callback)
        {
            var stream = client.TcpClient.GetStream();

            if (compress)
            {
                Compress(ref buffer, ref len);
            }

            var count = 0;

            while (count < len)
            {
                var block = buffer.Skip(count).Take(client.TcpClient.SendBufferSize).ToArray();

                stream.Write(block, 0, block.Length);

                count += block.Length;
            }

            if (callback != null)
            {
                callback(client, buffer);
            }
        }
Пример #4
0
        private static void Connected(WebSocketsClient client)
        {
            lock (Clients)
            {
                if (!Clients.Contains(client))
                {
                    Clients.Add(client);
                }
            }

            CMOptions.ToConsole("[{0}] Client connected: {1}", Clients.Count, client.Address);

            if (OnConnected != null)
            {
                VitaNexCore.TryCatch(
                    () => OnConnected(client),
                    e =>
                {
                    CMOptions.ToConsole(e);

                    client.Dispose();
                    Disconnected(client);
                });
            }
        }
Пример #5
0
        private static void Disconnected(WebSocketsClient client)
        {
            if (OnDisconnected != null)
            {
                VitaNexCore.TryCatch(() => OnDisconnected(client), CMOptions.ToConsole);
            }

            lock (Clients)
            {
                Clients.Remove(client);
            }

            CMOptions.ToConsole("[{0}] Client disconnected: {1}", Clients.Count, client.Address);

            client.Dispose();
        }
Пример #6
0
        private static void Receive(
            WebSocketsClient client,
            bool decompress,
            bool decode,
            Action <WebSocketsClient, string, byte[]> callback)
        {
            VitaNexCore.TryCatch(
                () =>
            {
                var stream = client.TcpClient.GetStream();

                var buffer = new byte[client.TcpClient.ReceiveBufferSize];
                var len    = buffer.Length;

                stream.Read(buffer, 0, buffer.Length);

                if (decompress)
                {
                    Decompress(ref buffer, ref len);
                }

                string data;

                if (decode)
                {
                    Decode(buffer, out data);
                }
                else
                {
                    data = new String(buffer.Select(b => (char)b).ToArray());
                }

                if (callback != null)
                {
                    callback(client, data, buffer);
                }
            },
                CMOptions.ToConsole);
        }
Пример #7
0
        private static void HandleConnection(WebSocketsClient client)
        {
            VitaNexCore.TryCatch(
                () =>
            {
                if (client.Seeded)
                {
                    return;
                }

                var headers = new Dictionary <string, string>();

                Receive(
                    client,
                    false,
                    true,
                    (c, d, b) =>
                {
                    if (d.Length == 0)
                    {
                        return;
                    }

                    var lines = d.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                    lines = lines.Take(lines.Length - 1).ToArray();

                    if (CMOptions.ModuleDebug)
                    {
                        CMOptions.ToConsole(lines.Not(String.IsNullOrWhiteSpace).ToArray());
                    }

                    lines.ForEach(
                        line =>
                    {
                        line = line.Trim();

                        var header = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                        if (header.Length == 0)
                        {
                            return;
                        }

                        var hk = header[0].Replace(":", String.Empty);

                        if (String.IsNullOrWhiteSpace(hk))
                        {
                            return;
                        }

                        var hv = header.Length > 1 ? String.Join(" ", header.Skip(1)) : String.Empty;

                        if (!headers.ContainsKey(hk))
                        {
                            headers.Add(hk, hv);
                        }
                        else
                        {
                            headers[hk] = hv;
                        }
                    });
                });

                if (headers.Count > 0)
                {
                    HandleHttpRequest(client, headers);
                }
                else
                {
                    throw new Exception("No headers defined for WebSockets client handshake.", new SocketException());
                }
            },
                CMOptions.ToConsole);
        }
Пример #8
0
		private static void HandleConnection(WebSocketsClient client)
		{
			VitaNexCore.TryCatch(
				() =>
				{
					if (client.Seeded)
					{
						return;
					}

					var headers = new Dictionary<string, string>();

					Receive(
						client,
						false,
						true,
						(c, d, b) =>
						{
							if (d.Length == 0)
							{
								return;
							}

							var lines = d.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);

							lines = lines.Take(lines.Length - 1).ToArray();

							if (CMOptions.ModuleDebug)
							{
								CMOptions.ToConsole(lines.Not(String.IsNullOrWhiteSpace).ToArray());
							}

							lines.ForEach(
								line =>
								{
									line = line.Trim();

									var header = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

									if (header.Length == 0)
									{
										return;
									}

									var hk = header[0].Replace(":", String.Empty);

									if (String.IsNullOrWhiteSpace(hk))
									{
										return;
									}

									var hv = header.Length > 1 ? String.Join(" ", header.Skip(1)) : String.Empty;

									if (!headers.ContainsKey(hk))
									{
										headers.Add(hk, hv);
									}
									else
									{
										headers[hk] = hv;
									}
								});
						});

					if (headers.Count > 0)
					{
						HandleHttpRequest(client, headers);
					}
					else
					{
						throw new Exception("No headers defined for WebSockets client handshake.", new SocketException());
					}
				},
				CMOptions.ToConsole);
		}
Пример #9
0
		private static void HandleHttpRequest(WebSocketsClient client, Dictionary<string, string> headers)
		{
			//var uri = headers["GET"];
			//var origin = headers["Origin"];

			var key = client.ResolveKey(headers["Sec-WebSocket-Key"]);

			var answer = Convert.ToBase64String(Encoding.ASCII.GetBytes(key.Value));

			var sendHeaders = new List<string>
			{
				"HTTP/1.1 101 Switching Protocols", //
				"Connection: Upgrade", //
				"Sec-WebSocket-Accept: " + answer, //
				"Upgrade: websocket" //
			};

			Send(client, String.Join("\r\n", sendHeaders) + "\r\n\r\n", false, false, (c, d) => client.Start());

			if (!CMOptions.ModuleDebug)
			{
				return;
			}

			CMOptions.ToConsole("HEADERS>>>\n");
			CMOptions.ToConsole(sendHeaders.ToArray());
		}
Пример #10
0
		private static void Receive(
			WebSocketsClient client,
			bool decompress,
			bool decode,
			Action<WebSocketsClient, string, byte[]> callback)
		{
			VitaNexCore.TryCatch(
				() =>
				{
					var stream = client.TcpClient.GetStream();

					var buffer = new byte[client.TcpClient.ReceiveBufferSize];
					var len = buffer.Length;

					stream.Read(buffer, 0, buffer.Length);

					if (decompress)
					{
						Decompress(ref buffer, ref len);
					}

					string data;

					if (decode)
					{
						Decode(buffer, out data);
					}
					else
					{
						data = new String(buffer.Select(b => (char)b).ToArray());
					}

					if (callback != null)
					{
						callback(client, data, buffer);
					}
				},
				CMOptions.ToConsole);
		}
Пример #11
0
		private static void Send(
			WebSocketsClient client,
			byte[] buffer,
			int len,
			bool compress,
			Action<WebSocketsClient, byte[]> callback)
		{
			var stream = client.TcpClient.GetStream();

			if (compress)
			{
				Compress(ref buffer, ref len);
			}

			var count = 0;

			while (count < len)
			{
				var block = buffer.Skip(count).Take(client.TcpClient.SendBufferSize).ToArray();

				stream.Write(block, 0, block.Length);

				count += block.Length;
			}

			if (callback != null)
			{
				callback(client, buffer);
			}
		}
Пример #12
0
		private static void Send(
			WebSocketsClient client,
			string data,
			bool encode,
			bool compress,
			Action<WebSocketsClient, byte[]> callback)
		{
			VitaNexCore.TryCatch(
				() =>
				{
					int len;
					byte[] buffer;

					if (encode)
					{
						Encode(data, out buffer, out len);
					}
					else
					{
						buffer = data.Select(c => (byte)c).ToArray();
						len = buffer.Length;
					}

					Send(client, buffer, len, compress, callback);
				},
				CMOptions.ToConsole);
		}
Пример #13
0
		private static void Disconnected(WebSocketsClient client)
		{
			if (OnDisconnected != null)
			{
				VitaNexCore.TryCatch(() => OnDisconnected(client), CMOptions.ToConsole);
			}

			lock (Clients)
			{
				Clients.Remove(client);
			}

			CMOptions.ToConsole("[{0}] Client disconnected: {1}", Clients.Count, client.Address);

			client.Dispose();
		}
Пример #14
0
		private static void Connected(WebSocketsClient client)
		{
			lock (Clients)
			{
				if (!Clients.Contains(client))
				{
					Clients.Add(client);
				}
			}

			CMOptions.ToConsole("[{0}] Client connected: {1}", Clients.Count, client.Address);

			if (OnConnected != null)
			{
				VitaNexCore.TryCatch(
					() => OnConnected(client),
					e =>
					{
						CMOptions.ToConsole(e);

						client.Dispose();
						Disconnected(client);
					});
			}
		}