Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

feat: replace `NetCoreServer` in IPC implementation (#358)

lars-berger5274ce884ea7
diff --git a/GlazeWM.App.Cli/CliStartup.cs b/GlazeWM.App.Cli/CliStartup.cs
index 9ff57ee7..ba692ece 100644
--- a/GlazeWM.App.Cli/CliStartup.cs
+++ b/GlazeWM.App.Cli/CliStartup.cs
@@ -1,4 +1,3 @@
-using System.Reactive.Linq;
using System.Text.Json;
using GlazeWM.Infrastructure.Common;
using GlazeWM.Infrastructure.Utils;
@@ -12,72 +11,55 @@ namespace GlazeWM.App.Cli
int ipcServerPort,
bool isSubscribeMessage)
{
- var client = new WebsocketClient(ipcServerPort);
+ var client = new WebSocketClient(ipcServerPort);
try
{
- var isConnected = client.Connect();
+ await client.ConnectAsync(CancellationToken.None);
- if (!isConnected)
- throw new Exception("Unable to connect to IPC server.");
-
- client.ReceiveAsync();
-
- var message = string.Join(" ", args);
- var sendSuccess = client.SendTextAsync(message);
-
- if (!sendSuccess)
- throw new Exception("Failed to send message to IPC server.");
-
- var serverMessages = GetMessagesObservable(client);
+ var clientMessage = string.Join(" ", args);
+ await client.SendTextAsync(clientMessage, CancellationToken.None);
// Wait for server to respond with a message.
- var firstMessage = await serverMessages
- .Timeout(TimeSpan.FromSeconds(5))
- .FirstAsync();
+ var serverResponse = await client.ReceiveTextAsync(CancellationToken.None);
// Exit on first message received when not subscribing to an event.
if (!isSubscribeMessage)
{
- Console.WriteLine(firstMessage);
- client.Disconnect();
+ var parsedMessage = ParseMessage(serverResponse);
+ Console.WriteLine(parsedMessage);
+ await client.DisconnectAsync(CancellationToken.None);
return ExitCode.Success;
}
- // Special handling is needed for event subscriptions.
- serverMessages.Subscribe(
- onNext: Console.WriteLine,
- onError: Console.Error.WriteLine
- );
-
- var _ = Console.ReadLine();
-
- client.Disconnect();
- return ExitCode.Success;
+ // When subscribing to events, continuously listen for server messages.
+ while (true)
+ {
+ var message = await client.ReceiveTextAsync(CancellationToken.None);
+ var parsedMessage = ParseMessage(message);
+ Console.WriteLine(parsedMessage);
+ }
}
catch (Exception exception)
{
Console.Error.WriteLine(exception.Message);
- client.Disconnect();
+ await client.DisconnectAsync(CancellationToken.None);
return ExitCode.Error;
}
}
/// <summary>
- /// Get `IObservable` of parsed server messages.
+ /// Parse JSON in server message.
/// </summary>
- private static IObservable<string> GetMessagesObservable(WebsocketClient client)
+ private static string ParseMessage(string message)
{
- return client.Messages.Select(message =>
- {
- var parsedMessage = JsonDocument.Parse(message).RootElement;
- var error = parsedMessage.GetProperty("error").GetString();
+ var parsedMessage = JsonDocument.Parse(message).RootElement;
+ var error = parsedMessage.GetProperty("error").GetString();
- if (error is not null)
- throw new Exception(error);
+ if (error is not null)
+ throw new Exception(error);
- return parsedMessage.GetProperty("data").ToString();
- });
+ return parsedMessage.GetProperty("data").ToString();
}
}
}
diff --git a/GlazeWM.App.IpcServer/DependencyInjection.cs b/GlazeWM.App.IpcServer/DependencyInjection.cs
index 718b2715..dbc1c539 100644
--- a/GlazeWM.App.IpcServer/DependencyInjection.cs
+++ b/GlazeWM.App.IpcServer/DependencyInjection.cs
@@ -7,7 +7,7 @@ namespace GlazeWM.App.IpcServer
public static IServiceCollection AddIpcServerServices(this IServiceCollection services)
{
services.AddSingleton<IpcMessageHandler>();
- services.AddSingleton<IpcServerManager>();
+ services.AddSingleton<IpcServerStartup>();
return services;
}
diff --git a/GlazeWM.App.IpcServer/GlazeWM.App.IpcServer.csproj b/GlazeWM.App.IpcServer/GlazeWM.App.IpcServer.csproj
index 838f54da..30ac785a 100644
--- a/GlazeWM.App.IpcServer/GlazeWM.App.IpcServer.csproj
+++ b/GlazeWM.App.IpcServer/GlazeWM.App.IpcServer.csproj
@@ -1,6 +1,7 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7-windows10.0.17763.0</TargetFramework>
+ <OutputType>Library</OutputType>
<DebugType>embedded</DebugType>
<Nullable>enable</Nullable>
</PropertyGroup>
diff --git a/GlazeWM.App.IpcServer/IpcMessageHandler.cs b/GlazeWM.App.IpcServer/IpcMessageHandler.cs
index 97b59fb4..d9924c68 100644
--- a/GlazeWM.App.IpcServer/IpcMessageHandler.cs
+++ b/GlazeWM.App.IpcServer/IpcMessageHandler.cs
@@ -1,8 +1,12 @@
using System;
-using System.Collections.Generic;
using System.Linq;
+using System.Net.WebSockets;
+using System.Reactive.Linq;
+using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
using CommandLine;
using GlazeWM.App.IpcServer.Messages;
using GlazeWM.App.IpcServer.Server;
@@ -13,7 +17,6 @@ using GlazeWM.Domain.Windows;
using GlazeWM.Domain.Workspaces;
using GlazeWM.Infrastructure.Bussing;
using GlazeWM.Infrastructure.Serialization;
-using GlazeWM.Infrastructure.Utils;
using Microsoft.Extensions.Logging;
namespace GlazeWM.App.IpcServer
@@ -35,11 +38,6 @@ namespace GlazeWM.App.IpcServer
options.Converters.Add(new JsonContainerConverter());
});
- /// <summary>
- /// Dictionary of event names and session IDs subscribed to that event.
- /// </summary>
- internal Dictionary<string, List<Guid>> SubscribedSessions = new();
-
/// <summary>
/// Matches words separated by spaces when not surrounded by double quotes.
/// Example: "a \"b c\" d" -> ["a", "\"b c\"", "d"]
@@ -64,19 +62,54 @@ namespace GlazeWM.App.IpcServer
_windowService = windowService;
}
- internal string GetResponseMessage(ClientMessage message)
+ internal async Task Handle(WebSocket ws)
{
- var (sessionId, messageString) = message;
+ var buffer = new byte[1024];
- _logger.LogDebug(
- "IPC message from session {Session}: {Message}.",
- sessionId,
- messageString
- );
+ while (ws.State == WebSocketState.Open)
+ {
+ try
+ {
+ var received = await ws.ReceiveAsync(
+ new ArraySegment<byte>(buffer),
+ CancellationToken.None
+ );
+
+ // Handle close messages.
+ if (received.MessageType == WebSocketMessageType.Close)
+ await ws.CloseAsync(
+ received.CloseStatus ?? WebSocketCloseStatus.NormalClosure,
+ received.CloseStatusDescription,
+ CancellationToken.None
+ );
+
+ // Ignore messages that aren't text.
+ if (received.MessageType != WebSocketMessageType.Text)
+ continue;
+
+ var clientMessage = Encoding.UTF8.GetString(buffer, 0, received.Count);
+ var serverMessage = GetResponseMessage(clientMessage, ws);
+
+ await ws.SendAsync(
+ serverMessage,
+ WebSocketMessageType.Text,
+ true,
+ CancellationToken.None
+ );
+ }
+ catch
+ {
+ }
+ }
+ }
+
+ private ArraySegment<byte> GetResponseMessage(string message, WebSocket ws)
+ {
+ _logger.LogDebug("IPC message received: {Message}.", message);
try
{
- var messageParts = _messagePartsRegex.Matches(messageString)
+ var messageParts = _messagePartsRegex.Matches(message)
.Select(match => match.Value)
.Where(match => match is not null);
@@ -91,26 +124,28 @@ namespace GlazeWM.App.IpcServer
object? data = parsedArgs.Value switch
{
InvokeCommandMessage commandMsg => HandleInvokeCommandMessage(commandMsg),
- SubscribeMessage subscribeMsg => HandleSubscribeMessage(subscribeMsg, sessionId),
+ SubscribeMessage subscribeMsg => HandleSubscribeMessage(subscribeMsg, ws),
GetMonitorsMessage => _monitorService.GetMonitors(),
GetWorkspacesMessage => _workspaceService.GetActiveWorkspaces(),
GetWindowsMessage => _windowService.GetWindows(),
- _ => throw new Exception($"Invalid message '{messageString}'")
+ _ => throw new Exception($"Invalid message '{message}'")
};
- return ToResponseMessage(
+ return ToServerMessage(
success: true,
+ messageType: ServerMessageType.ClientResponse,
data: data,
- clientMessage: messageString
+ clientMessage: message
);
}
catch (Exception exception)
{
- return ToResponseMessage<bool?>(
+ return ToServerMessage(
success: false,
+ messageType: ServerMessageType.ClientResponse,
data: null,
- clientMessage: messageString,
- error: exception.Message
+ error: exception.Message,
+ clientMessage: message
);
}
}
@@ -118,8 +153,9 @@ namespace GlazeWM.App.IpcServer
private bool? HandleInvokeCommandMessage(InvokeCommandMessage message)
{
var contextContainer =
- _containerService.GetContainerById(Guid.Parse(message.ContextContainerId)) ??
- _containerService.FocusedContainer;
+ message.ContextContainerId is not null
+ ? _containerService.GetContainerById(Guid.Parse(message.ContextContainerId))
+ : _containerService.FocusedContainer;
var commandString = CommandParsingService.FormatCommand(message.Command);
@@ -132,52 +168,52 @@ namespace GlazeWM.App.IpcServer
return null;
}
- private bool? HandleSubscribeMessage(SubscribeMessage message, Guid sessionId)
+ private bool? HandleSubscribeMessage(SubscribeMessage message, WebSocket ws)
{
- foreach (var eventName in message.Events.Split(','))
- {
- if (SubscribedSessions.ContainsKey(eventName))
- {
- var sessionIds = SubscribedSessions.GetValueOrThrow(eventName);
- sessionIds.Add(sessionId);
- continue;
- }
+ var eventNames = message.Events.Split(',');
- SubscribedSessions.Add(eventName, new() { sessionId });
- }
+ _bus.Events
+ .TakeWhile((_) => ws.State == WebSocketState.Open)
+ .Where(@event => eventNames.Contains(@event.FriendlyName))
+ .Subscribe((@event) =>
+ {
+ var serverMessage = ToServerMessage(
+ success: true,
+ messageType: ServerMessageType.SubscribedEvent,
+ data: @event
+ );
+
+ _ = ws.SendAsync(
+ serverMessage,
+ WebSocketMessageType.Text,
+ true,
+ CancellationToken.None
+ );
+ });
return null;
}
- private string ToResponseMessage<T>(
+ private ArraySegment<byte> ToServerMessage(
bool success,
- T? data,
- string clientMessage,
- string? error = null)
+ ServerMessageType messageType,
+ object? data,
+ string? error = null,
+ string? clientMessage = null)
{
- var responseMessage = new ServerMessage<T>(
+ // Use `object` type so that the JSON serializer uses derived type.
+ var serverMessage = new ServerMessage<object>(
Success: success,
- MessageType: ServerMessageType.ClientResponse,
+ MessageType: messageType,
Data: data,
Error: error,
ClientMessage: clientMessage
);
- return JsonParser.ToString(responseMessage, _serializeOptions);
- }
-
- internal string ToEventMessage(Event @event)
- {
- // Set type to `object` so that the JSON serializer uses derived `Event` type.
- var eventMessage = new ServerMessage<object>(
- Success: true,
- MessageType: ServerMessageType.SubscribedEvent,
- Data: @event,
- Error: null,
- ClientMessage: null
- );
+ var messageString = JsonParser.ToString(serverMessage, _serializeOptions);
+ var messageBytes = Encoding.UTF8.GetBytes(messageString);
- return JsonParser.ToString(eventMessage, _serializeOptions);
+ return new ArraySegment<byte>(messageBytes);
}
}
}
diff --git a/GlazeWM.App.IpcServer/IpcServerManager.cs b/GlazeWM.App.IpcServer/IpcServerManager.cs
deleted file mode 100644
index 0a612d71..00000000
--- a/GlazeWM.App.IpcServer/IpcServerManager.cs
+++ /dev/null
@@ -1,100 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Reactive.Linq;
-using System.Reactive.Subjects;
-using GlazeWM.App.IpcServer.Server;
-using GlazeWM.Infrastructure.Bussing;
-using Microsoft.Extensions.Logging;
-
-namespace GlazeWM.App.IpcServer
-{
- public sealed class IpcServerManager : IDisposable
- {
- private readonly Bus _bus;
- private readonly IpcMessageHandler _ipcMessageHandler;
- private readonly ILogger<IpcServerManager> _logger;
-
- /// <summary>
- /// The websocket server instance.
- /// </summary>
- private Server.IpcServer? _server { get; set; }
-
- private readonly Subject<bool> _serverKill = new();
-
- public IpcServerManager(
- Bus bus,
- IpcMessageHandler ipcMessageHandler,
- ILogger<IpcServerManager> logger)
- {
- _bus = bus;
- _ipcMessageHandler = ipcMessageHandler;
- _logger = logger;
- }
-
- /// <summary>
- /// Start the IPC server on specified port.
- /// </summary>
- public void StartServer(int port)
- {
- _server = new(port);
- _server.Start();
-
- // Start listening for messages.
- _server.Messages
- .TakeUntil(_serverKill)
- .Subscribe(clientMessage =>
- {
- var responseMessage = _ipcMessageHandler.GetResponseMessage(clientMessage);
- SendToSession(clientMessage.SessionId, responseMessage);
- });
-
- // Broadcast events to subscribed sessions.
- _bus.Events
- .TakeUntil(_serverKill)
- .Subscribe(@event =>
- {
- var subscribedSessionIds =
- _ipcMessageHandler.SubscribedSessions.GetValueOrDefault(
- @event.FriendlyName,
- new List<Guid>()
- );
-
- foreach (var sessionId in subscribedSessionIds)
- {
- var responseMessage = _ipcMessageHandler.ToEventMessage(@event);
- SendToSession(sessionId, responseMessage);
- }
- });
-
- _logger.LogDebug("Started IPC server on port {Port}.", port);
- }
-
- /// <summary>
- /// Kill the IPC server.
- /// </summary>
- public void StopServer()
- {
- if (_server is null)
- return;
-
- _serverKill.OnNext(true);
- _server.Stop();
- _logger.LogDebug("Stopped IPC server on port {Port}.", _server.Port);
- }
-
- /// <summary>
- /// Send text message to given session ID.
- /// </summary>
- private void SendToSession(Guid sessionId, string text)
- {
- var session = _server?.FindSession(sessionId) as IpcSession;
- session?.SendTextAsync(text);
- }
-
- public void Dispose()
- {
- if (_server?.IsDisposed != true)
- _server?.Dispose();
- }
- }
-}
diff --git a/GlazeWM.App.IpcServer/IpcServerStartup.cs b/GlazeWM.App.IpcServer/IpcServerStartup.cs
new file mode 100644
index 00000000..22c24a7d
--- /dev/null
+++ b/GlazeWM.App.IpcServer/IpcServerStartup.cs
@@ -0,0 +1,46 @@
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Logging;
+
+namespace GlazeWM.App.IpcServer
+{
+ public sealed class IpcServerStartup
+ {
+ private readonly ILogger<IpcServerStartup> _logger;
+ private readonly IpcMessageHandler _ipcMessageHandler;
+
+ public IpcServerStartup(
+ ILogger<IpcServerStartup> logger,
+ IpcMessageHandler ipcMessageHandler)
+ {
+ _logger = logger;
+ _ipcMessageHandler = ipcMessageHandler;
+ }
+
+ /// <summary>
+ /// Start the IPC server on specified port.
+ /// </summary>
+ public void Run(int port)
+ {
+ _logger.LogDebug("Starting IPC server on port {Port}.", port);
+
+ var builder = WebApplication.CreateBuilder();
+ builder.Logging.ClearProviders();
+ builder.WebHost.UseUrls($"http://localhost:{port}");
+
+ var app = builder.Build();
+ app.UseWebSockets();
+
+ app.Use(async (context, next) =>
+ {
+ if (!context.WebSockets.IsWebSocketRequest)
+ await next();
+
+ using var ws = await context.WebSockets.AcceptWebSocketAsync();
+ await _ipcMessageHandler.Handle(ws);
+ });
+
+ app.Run();
+ }
+ }
+}
diff --git a/GlazeWM.App.IpcServer/Server/ClientMessage.cs b/GlazeWM.App.IpcServer/Server/ClientMessage.cs
deleted file mode 100644
index bdf82370..00000000
--- a/GlazeWM.App.IpcServer/Server/ClientMessage.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-using System;
-
-namespace GlazeWM.App.IpcServer.Server
-{
- internal sealed record ClientMessage(Guid SessionId, string Message);
-}
diff --git a/GlazeWM.App.IpcServer/Server/IpcServer.cs b/GlazeWM.App.IpcServer/Server/IpcServer.cs
deleted file mode 100644
index 437bbee6..00000000
--- a/GlazeWM.App.IpcServer/Server/IpcServer.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-using System.Net;
-using System.Reactive.Subjects;
-using NetCoreServer;
-
-namespace GlazeWM.App.IpcServer.Server
-{
- internal sealed class IpcServer : WsServer
- {
- /// <summary>
- /// Messages received from all websocket sessions.
- /// </summary>
- public readonly Subject<ClientMessage> Messages = new();
-
- public IpcServer(int port) : base(IPAddress.Any, port)
- {
- }
-
- protected override TcpSession CreateSession()
- {
- return new IpcSession(this);
- }
-
- protected override void Dispose(bool disposingManagedResources)
- {
- if (disposingManagedResources)
- Messages.Dispose();
-
- base.Dispose(disposingManagedResources);
- }
- }
-}
diff --git a/GlazeWM.App.IpcServer/Server/IpcSession.cs b/GlazeWM.App.IpcServer/Server/IpcSession.cs
deleted file mode 100644
index a0bf3882..00000000
--- a/GlazeWM.App.IpcServer/Server/IpcSession.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System.Text;
-using NetCoreServer;
-
-namespace GlazeWM.App.IpcServer.Server
-{
- internal sealed class IpcSession : WsSession
- {
- public IpcSession(IpcServer server) : base(server)
- {
- }
-
- /// <summary>
- /// Emit received text buffers to `Messages` subject of the server.
- /// </summary>
- public override void OnWsReceived(byte[] buffer, long offset, long size)
- {
- var text = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
-
- if (Server is IpcServer server)
- server.Messages.OnNext(new ClientMessage(Id, text));
- }
- }
-}
diff --git a/GlazeWM.App.IpcServer/Server/ServerMessage.cs b/GlazeWM.App.IpcServer/ServerMessage.cs
similarity index 100%
rename from GlazeWM.App.IpcServer/Server/ServerMessage.cs
rename to GlazeWM.App.IpcServer/ServerMessage.cs
diff --git a/GlazeWM.App.IpcServer/Server/ServerMessageType.cs b/GlazeWM.App.IpcServer/ServerMessageType.cs
similarity index 100%
rename from GlazeWM.App.IpcServer/Server/ServerMessageType.cs
rename to GlazeWM.App.IpcServer/ServerMessageType.cs
diff --git a/GlazeWM.App/Program.cs b/GlazeWM.App/Program.cs
index 492a1f41..3f9722b9 100644
--- a/GlazeWM.App/Program.cs
+++ b/GlazeWM.App/Program.cs
@@ -80,15 +80,15 @@ namespace GlazeWM.App
ServiceLocator.Provider = BuildWmServiceProvider(options);
- var (barService, ipcServerManager, wmStartup) =
+ var (barService, ipcServerStartup, wmStartup) =
ServiceLocator.GetRequiredServices<
BarService,
- IpcServerManager,
+ IpcServerStartup,
WmStartup
>();
ThreadUtils.CreateSTA("GlazeWMBar", barService.StartApp);
- ThreadUtils.Create("GlazeWMIPC", () => ipcServerManager.StartServer(IpcServerPort));
+ ThreadUtils.Create("GlazeWMIPC", () => ipcServerStartup.Run(IpcServerPort));
// Run the window manager on the main thread.
return wmStartup.Run();
diff --git a/GlazeWM.Domain/UserConfigs/CommandParsingService.cs b/GlazeWM.Domain/UserConfigs/CommandParsingService.cs
index 7793da32..9f287070 100644
--- a/GlazeWM.Domain/UserConfigs/CommandParsingService.cs
+++ b/GlazeWM.Domain/UserConfigs/CommandParsingService.cs
@@ -61,10 +61,41 @@ namespace GlazeWM.Domain.UserConfigs
}
public void ValidateCommand(string commandString)
+ {
+ ParseCommand(commandString, null);
+ }
+
+ public Command ParseCommand(string commandString, Container subjectContainer)
{
try
{
- ParseCommand(commandString, null);
+ var commandParts = commandString.Split(" ");
+
+ return commandParts[0] switch
+ {
+ "tiling" => ParseTilingCommand(commandParts, subjectContainer),
+ // TODO: "layout <LAYOUT>" commands are deprecated. Remove in next major release.
+ "layout" => ParseLayoutCommand(commandParts, subjectContainer),
+ "focus" => ParseFocusCommand(commandParts),
+ "move" => ParseMoveCommand(commandParts, subjectContainer),
+ "resize" => ParseResizeCommand(commandParts, subjectContainer),
+ "set" => ParseSetCommand(commandParts, subjectContainer),
+ "toggle" => ParseToggleCommand(commandParts, subjectContainer),
+ "exit" => ParseExitCommand(commandParts),
+ "close" => subjectContainer is Window
+ ? new CloseWindowCommand(subjectContainer as Window)
+ : new NoopCommand(),
+ "reload" => ParseReloadCommand(commandParts),
+ "exec" => new ExecProcessCommand(
+ ExtractProcessName(string.Join(" ", commandParts[1..])),
+ ExtractProcessArgs(string.Join(" ", commandParts[1..]))
+ ),
+ "ignore" => subjectContainer is Window
+ ? new IgnoreWindowCommand(subjectContainer as Window)
+ : new NoopCommand(),
+ "binding" => ParseBindingCommand(commandParts),
+ _ => throw new ArgumentException(null, nameof(commandString)),
+ };
}
catch
{
@@ -72,37 +103,6 @@ namespace GlazeWM.Domain.UserConfigs
}
}
- public Command ParseCommand(string commandString, Container subjectContainer)
- {
- var commandParts = commandString.Split(" ");
-
- return commandParts[0] switch
- {
- "tiling" => ParseTilingCommand(commandParts, subjectContainer),
- // TODO: "layout <LAYOUT>" commands are deprecated. Remove in next major release.
- "layout" => ParseLayoutCommand(commandParts, subjectContainer),
- "focus" => ParseFocusCommand(commandParts),
- "move" => ParseMoveCommand(commandParts, subjectContainer),
- "resize" => ParseResizeCommand(commandParts, subjectContainer),
- "set" => ParseSetCommand(commandParts, subjectContainer),
- "toggle" => ParseToggleCommand(commandParts, subjectContainer),
- "exit" => ParseExitCommand(commandParts),
- "close" => subjectContainer is Window
- ? new CloseWindowCommand(subjectContainer as Window)
- : new NoopCommand(),
- "reload" => ParseReloadCommand(commandParts),
- "exec" => new ExecProcessCommand(
- ExtractProcessName(string.Join(" ", commandParts[1..])),
- ExtractProcessArgs(string.Join(" ", commandParts[1..]))
- ),
- "ignore" => subjectContainer is Window
- ? new IgnoreWindowCommand(subjectContainer as Window)
- : new NoopCommand(),
- "binding" => ParseBindingCommand(commandParts),
- _ => throw new ArgumentException(null, nameof(commandString)),
- };
- }
-
private static Command ParseTilingCommand(string[] commandParts, Container subjectContainer)
{
return commandParts[1] switch
diff --git a/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj b/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj
index a0ec5012..fe39f419 100644
--- a/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj
+++ b/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj
@@ -55,8 +55,5 @@
<PackageReference
Include="ManagedShell"
Version="0.0.198" />
- <PackageReference
- Include="NetCoreServer"
- Version="6.7.0" />
</ItemGroup>
</Project>
diff --git a/GlazeWM.Infrastructure/Utils/WebSocketClient.cs b/GlazeWM.Infrastructure/Utils/WebSocketClient.cs
new file mode 100644
index 00000000..9b47dad5
--- /dev/null
+++ b/GlazeWM.Infrastructure/Utils/WebSocketClient.cs
@@ -0,0 +1,71 @@
+using System;
+using System.Net.WebSockets;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace GlazeWM.Infrastructure.Utils
+{
+ public class WebSocketClient
+ {
+ private readonly ClientWebSocket _ws = new();
+ private readonly string _address;
+ private readonly int _port;
+
+ public WebSocketClient(string address, int port)
+ {
+ _address = address;
+ _port = port;
+ }
+
+ public WebSocketClient(int port)
+ {
+ _address = "localhost";
+ _port = port;
+ }
+
+ public async Task ConnectAsync(CancellationToken cancellationToken)
+ {
+ await _ws.ConnectAsync(
+ new Uri($"ws://{_address}:{_port}"),
+ cancellationToken
+ );
+ }
+
+ public async Task<string> ReceiveTextAsync(CancellationToken cancellationToken)
+ {
+ var buffer = new byte[1024 * 4];
+
+ // Continuously listen until a text message is received.
+ while (true)
+ {
+ var result = await _ws.ReceiveAsync(
+ new ArraySegment<byte>(buffer),
+ cancellationToken
+ );
+
+ if (result.MessageType != WebSocketMessageType.Text)
+ continue;
+
+ return Encoding.UTF8.GetString(buffer, 0, result.Count);
+ }
+ }
+
+ public async Task SendTextAsync(string message, CancellationToken cancellationToken)
+ {
+ var messageBytes = Encoding.UTF8.GetBytes(message);
+
+ await _ws.SendAsync(
+ new ArraySegment<byte>(messageBytes),
+ WebSocketMessageType.Text,
+ true,
+ cancellationToken
+ );
+ }
+
+ public async Task DisconnectAsync(CancellationToken cancellationToken)
+ {
+ await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, null, cancellationToken);
+ }
+ }
+}
diff --git a/GlazeWM.Infrastructure/Utils/WebsocketClient.cs b/GlazeWM.Infrastructure/Utils/WebsocketClient.cs
deleted file mode 100644
index f41b249b..00000000
--- a/GlazeWM.Infrastructure/Utils/WebsocketClient.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using System;
-using System.Reactive.Subjects;
-using System.Text;
-using NetCoreServer;
-
-namespace GlazeWM.Infrastructure.Utils
-{
- public class WebsocketClient : WsClient
- {
- /// <summary>
- /// Messages received from websocket server.
- /// </summary>
- public readonly ReplaySubject<string> Messages = new();
-
- public WebsocketClient(int port) : base("127.0.0.1", port) { }
-
- public WebsocketClient(string address, int port) : base(address, port) { }
-
- public override void OnWsConnecting(HttpRequest request)
- {
- request.SetBegin("GET", "/")
- .SetHeader("Host", "localhost")
- .SetHeader("Origin", "http://localhost")
- .SetHeader("Upgrade", "websocket")
- .SetHeader("Connection", "Upgrade")
- .SetHeader("Sec-WebSocket-Key", Convert.ToBase64String(WsNonce))
- .SetHeader("Sec-WebSocket-Protocol", "chat, superchat")
- .SetHeader("Sec-WebSocket-Version", "13")
- .SetBody();
- }
-
- public override void OnWsReceived(byte[] buffer, long offset, long size)
- {
- var message = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
- Messages.OnNext(message);
- }
- }
-}